I have this code here that in the end few lines is supposed to return my results through a JOptionPane window,
for(int i = 0; i < 10; i++) {
percent[i] = ((double)counts[i] / amount) * 100;
}
//create results
// results starting out is just the numbers. Remove the code from the for loop above that does that,
// and instead use a for loop and go through both arrays creating the output string results with
// the count and percentage of each of the 10 numbers one per line.
results = String.format("%-10s%-10s%-10s\n*****************************************\n", "Numbers:", "Count:","Percentage:");
for(int i = 0; i < 10; i++) {
int number = i + 1;
results += String.format("%-10s%-10s%-10s\n", number, counts[i], percent[i]);
}
results = results + "\n\nRepeat this? Yes or No";
// show results in a confirm dialog that will also control the loop
choice = JOptionPane.showConfirmDialog(null, results, "Results", 0);
}
but in turn just repeats the initial window requesting the input amount of random numbers. Am I over looking an issue?
Here is the whole code:
/* RandomCounts.java
*
* generates a certain amount of random numbers between 1 and 10
*
* Modify this code as follows:
*
* As is, this code just outputs the random numbers to a dialog box.
*
* Create two arrays where indicated: counts (int) and percents (double). Each of size 10
*
* initialize counts where indicated
*
* update counts where indicated, and remove code that updates results
*
* calculate percentages using a for loop where indicated
*
* output both arrays where indicated
*
* Remember: arrays are zero based. Your arrays of size 10 will have indices 0-9, NOT 1-10
*/
import java.awt.Font;
import javax.swing.*;
public class RandomCountsStart {
public static void main(String[] args) {
UIManager.put("OptionPane.messageFont", new Font(Font.MONOSPACED, Font.BOLD, 24));
int[] counts = new int[10];
double[] percent = new double[10];// Declare the arrays counts and percents here
int num = 0, amount = 0, choice=0;
String results;
while (choice == 0){
for(int i = 0; i < 10; i++){
counts[i] = 0;
}// initialize counts here using a for loop
String input = JOptionPane.showInputDialog(null, "Input the amount of random numbers to generate");
amount = Integer.parseInt(input);
results = "";
// generate the numbers in a for loop
for(int i = 1; i <= amount; i++){
num = (int)(Math.random()*10) + 1;
}
// here is where you should update the array counts based on which num was generated
// for example: if num is 3, update the array element that counts 3's
if(num == 1) {
counts[0]++;
}
else if(num == 2) {
counts[1]++;
}
else if(num == 3) {
counts[2]++;
}
else if(num == 4) {
counts[3]++;
}
else if(num == 5) {
counts[4]++;
}
else if(num == 6) {
counts[5]++;
}
else if(num == 7) {
counts[6]++;
}
else if(num == 8) {
counts[7]++;
}
else if(num == 9) {
counts[8]++;
}
else if(num == 10) {
counts[9]++;
}
}
// calculate percentages
// go through the count array and determine the percentage of each value. Store the
// percentage in the appropriate element in percents (parallel array example)
for(int i = 0; i < 10; i++) {
percent[i] = ((double)counts[i] / amount) * 100;
}
//create results
// results starting out is just the numbers. Remove the code from the for loop above that does that,
// and instead use a for loop and go through both arrays creating the output string results with
// the count and percentage of each of the 10 numbers one per line.
results = String.format("%-10s%-10s%-10s\n*****************************************\n", "Numbers:", "Count:","Percentage:");
for(int i = 0; i < 10; i++) {
int number = i + 1;
results += String.format("%-10s%-10s%-10s\n", number, counts[i], percent[i]);
}
results = results + "\n\nRepeat this? Yes or No";
// show results in a confirm dialog that will also control the loop
choice = JOptionPane.showConfirmDialog(null, results, "Results", 0);
}
}
so i've updated your code to include up until choice = JOptionPane.showConfirmDialog(null, results, "Results", 0); in your while loop.
/* RandomCounts.java
*
* generates a certain amount of random numbers between 1 and 10
*
* Modify this code as follows:
*
* As is, this code just outputs the random numbers to a dialog box.
*
* Create two arrays where indicated: counts (int) and percents (double). Each of size 10
*
* initialize counts where indicated
*
* update counts where indicated, and remove code that updates results
*
* calculate percentages using a for loop where indicated
*
* output both arrays where indicated
*
* Remember: arrays are zero based. Your arrays of size 10 will have indices 0-9, NOT 1-10
*/
import java.awt.Font;
import javax.swing.*;
public class RandomCountsStart {
public static void main(String[] args) {
UIManager.put("OptionPane.messageFont", new Font(Font.MONOSPACED, Font.BOLD, 24));
int[] counts = new int[10];
double[] percent = new double[10];// Declare the arrays counts and percents here
int num = 0;
int amount = 0;
int choice=0;
String results;
while (choice == 0){
for(int i = 0; i < 10; i++){
counts[i] = 0;
}// initialize counts here using a for loop
String input = JOptionPane.showInputDialog(null, "Input the amount of random numbers to generate");
amount = Integer.parseInt(input);
results = "";
// generate the numbers in a for loop
for(int i = 1; i <= amount; i++){
num = (int)(Math.random()*10) + 1;
}
// here is where you should update the array counts based on which num was generated
// for example: if num is 3, update the array element that counts 3's
if(num == 1) {
counts[0]++;
}
else if(num == 2) {
counts[1]++;
}
else if(num == 3) {
counts[2]++;
}
else if(num == 4) {
counts[3]++;
}
else if(num == 5) {
counts[4]++;
}
else if(num == 6) {
counts[5]++;
}
else if(num == 7) {
counts[6]++;
}
else if(num == 8) {
counts[7]++;
}
else if(num == 9) {
counts[8]++;
}
else if(num == 10) {
counts[9]++;
}
// calculate percentages
// go through the count array and determine the percentage of each value. Store the
// percentage in the appropriate element in percents (parallel array example)
for(int i = 0; i < 10; i++) {
percent[i] = ((double)counts[i] / amount) * 100;
}
//create results
// results starting out is just the numbers. Remove the code from the for loop above that does that,
// and instead use a for loop and go through both arrays creating the output string results with
// the count and percentage of each of the 10 numbers one per line.
results = String.format("%-10s%-10s%-10s\n*****************************************\n", "Numbers:", "Count:","Percentage:");
for(int i = 0; i < 10; i++) {
int number = i + 1;
results += String.format("%-10s%-10s%-10s\n", number, counts[i], percent[i]);
}
results = results + "\n\nRepeat this? Yes or No";
// show results in a confirm dialog that will also control the loop
choice = JOptionPane.showConfirmDialog(null, results, "Results", 0);
}
}
}
Related
I am still somewhat of a beginner to Java, but I need help with my code. I wanted to write an Armstrong Number checker.
An Armstrong number is one whose sum of digits raised to the power three equals the number itself. 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.
If I understand this concept correctly, then my code should work fine, but I don't know where I made mistakes. I would appreciate if you could help correct my mistakes, but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.
Here is the code:
public class ArmstrongChecker {
boolean confirm = false;
Integer input;
String converter;
int indices;
int result = 1;
void ArmstrongCheck(Integer input) {
this.input = input;
converter = input.toString();
char[] array = converter.toCharArray();
indices = array.length;
result = (int) Math.pow(array[0], indices);
for (int i = 1; i < array.length; i++) {
result = result + (int) Math.pow(array[i], indices);
}
if (result == input) {
confirm = true;
System.out.println(confirm);
} else {
System.out.println(confirm);
}
}
}
For my tries I used '153' as an input. Thank you for your help!
You aren't summing the digits, but the numeric values of the characters representing them. You can convert such a character to its numeric value by subtracting the character '0':
int result = 0;
for(int i = 0; i < array.length; i++) {
result = result + (int) Math.pow(array[i] - '0', indices);
}
Having said that, it's arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration. The number of digits itself can be calculated using a base-10 log.
int temp = input;
int result = 0;
int indices = (int) Math.log10(input) + 1;
while (temp != 0) {
int digit = temp % 10;
result += (int) Math.pow(digit, indices);
temp /= 10;
}
There is a small logical mistake in your code, You're not converting the character to an integer instead you're doing something like
Math.pow('1', 3) -> Math.pow(49, 3) // what you're doing
Math.pow(1, 3) // what should be done
You should first convert the character to the string using any method below
result = (int) Math.pow(array[0],indices);
for(int i = 1;i<array.length;i++) {
result = result + (int) Math.pow(array[i],indices);
}
For converting char to integer
int x = Character.getNumericValue(array[i]);
or
int x = Integer.parseInt(String.valueOf(array[i]));
or
int x = array[i] - '0';
Alternatively
You can also check for Armstrong's number without any conversion, using the logic below
public class Armstrong {
public static void main(String[] args) {
int number = 153, num, rem, res = 0;
num = number;
while (num != 0)
{
rem = num % 10;
res += Math.pow(rem, 3);
num /= 10;
}
if(res == num)
System.out.println("YES");
else
System.out.println("NO");
}
}
For any int >= 0 you can do it like this.
Print all the Armstrong numbers less than 10_000.
for (int i = 0; i < 10_000; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
prints
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
The key is to use Math.log10 to compute the number of digits in the candidate number. This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912. Casting to an int and adding 1 would be 3 digits.
The number of digits is then the power used for computation.
Then it's just a matter of summing up the digits raised to that power. The method short circuits and returns false if the sum exceeds the number before all the digits are processed.
public static boolean isArmstrong(int v) {
if (v < 0) {
throw new IllegalArgumentException("Argument must >= 0");
}
int temp = v;
int power = (int)Math.log10(temp)+1;
int sum = 0;
while (temp > 0) {
sum += Math.pow(temp % 10, power);
if (sum > v) {
return false;
}
temp/= 10;
}
return v == sum;
}
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.
Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.
import java.util.Scanner;
public class A5E4 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter an integer: ");
int friendlyNumber = in.nextInt();
boolean result = isFriendly(friendlyNumber);
if (result)
{
System.out.println("The integer is friendly");
}
else
{
System.out.println("The integer is not friendly");
}
}
public static boolean isFriendly(int number)
{
int counter = 1;
while (number / 10 >= 1)
{
counter ++;
number = number / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if (number / Math.pow(10, (counter - i)) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
}
while (number / 10 >= 1){
counter ++;
number = number / 10;
}
In this bit, you are reducing number to something smaller than 10. That is probably not what you want. You should make a copy of number here.
Also, proper software design would recommend that you extract this to a dedicated method.
private int countDigits(int number){
if(number < 1) throw new IllegalArgumentException();
int n = number;
int counter = 1;
while (n / 10 >= 1){
counter ++;
n = n / 10;
}
return counter;
}
You need to copy the number which you use to find out how much digits your number has. Otherwise you change the number itself and don't know anymore what it was.
The second mistake is that you divide an integer by Math.pow() which returns a double. So your result is double. You want to have an integer to use the modulo operator.
public static boolean isFriendly(int number)
{
int counter = 1;
int tmpNumber = number;
while (tmpNumber / 10 >= 1)
{
counter ++;
tmpNumber = tmpNumber / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if ((int)(number / Math.pow(10, (counter - i))) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
The first problem is that you are modifying the value of the number you are trying to check. So, if your method is called with 149, then after the while loop to count the digits, its value will be 1. So, you are always going to find that it is 'unfriendly'. Assuming you fix this so that number contains the number you are checking. Try this instead of your 'for' loop:
while ( counter && !( ( number % 10 / counter ) % counter ) )
{
number = number / 10;
counter--;
}
It works by taking the last digit of your number using the modulus or remainder operator and then divides this by the digit position and checks that the remainder is zero. If all is good, it decrements the counter until it reaches zero, otherwise it terminates before counter is zero.
Try something like this (change your isFriendly() method):
public static boolean isFriendly(int number)
{
String numberAsString = String.valueOf(number); //Convert the int as a String to make it easier to iterate through
for(int i = 0; i < numberAsString.length(); i++) {
int currentDigit = Character.getNumericValue(numberAsString.charAt(numberAsString.length() - i - 1)); //Iterate over the number backwards
System.out.println(currentDigit); //Print the current digit
if(currentDigit % (i + 1) != 0) {
return false;
}
}
return true;
}
The easy way is to convert to string and then check if it is friendly:
public static boolean isFriendly(int number)
{
String num = Integer.toString(number);
for (int i = 0, dividedBy = 1; i < num.length(); i++, dividedBy++)
{
String numToCheck = "";
for (int j = 0; j <= i; j++)
{
numToCheck += num.charAt(j);
}
if (Integer.valueOf(numToCheck) % dividedBy != 0) {
return false;
}
}
return true;
}
How can I count in Java the maximum consecutive 1's from a binary number?
For instance, the user enters an integer like 13 this would be in binary 1101.
The binary number 1101 has 2 consecutive one's, so the output should be 2.
Another example the number 5 would be in binary 0101, so the output should be 1. My program doesn't work correctly if I type the number 439.
Scanner scanner = new Scanner(System.in);
int numb = scanner.nextInt();
int tempCount = 0;
int count = 0;
// numb = 439 -> output 3
// numb = 13 -> output 2
// numb = 1 -> output 1
while (numb >= 1) {
if (numb % 2 != 0) {
tempCount++;
numb /= 2;
count = tempCount;
if (numb % 2 != 0) {
tempCount++;
count = tempCount;
numb /= 2;
}
}
else {
numb /= 2;
tempCount = 0;
}
}
System.out.println(count);
I figured it out, here is the solution.
I have forgotten an nested if statement.
Scanner scanner = new Scanner(System.in);
int numb = scanner.nextInt();
int tempCount = 0; //save temporarily the longest sequence of one's in this variable
int count = 0; // before the sequence of one's gets interrupted, I save the value from tempCount in count
// numb = 439 -> output 3
// numb = 13 -> output 2
// numb = 1 -> output 1
while (numb >= 1) {
if (numb % 2 != 0) {
tempCount++;
numb /= 2;
if(count < tempCount){
count = tempCount;
}
}
else {
numb /= 2;
tempCount = 0;
}
}
System.out.println(count);
I believe you intended count to be the length of the longest sequence of 1s, while tempCount is the number of 1s in the sequence your currently counting. So you should only assign tempCount to count if it is greater than count. For 439, I believe you are correctly counting three 1s. Then comes a 0, and you correctly reset tempCount to zero. Next time you count a 1, you correctly increment tempCount to one, then assign this one to count too, and your count of three gets lost.
We can identify two consecutive binary ones in the least significant positions like this:
(value & 0b11) == 0b11
We can move the bits in value to the right like so:
value >>>= 1;
It's important to use tripple >>> over double >> because we don't care about the sign bit.
Then all we have to do is keep track of the maximum number of consecutive 1s:
int countMax1Streak(int value) { // value could also be a long if required
int max = 0;
int count = 1;
while (value != 0) {
if ((value & 0b11) == 0b11) {
count++;
} else {
count = 1;
}
value >>>= 1;
if (count > max) {
max = count;
}
}
return max;
}
Test cases:
assertEquals(0, countMax1Streak(0b0));
assertEquals(1, countMax1Streak(0b1));
assertEquals(1, countMax1Streak(0b10));
assertEquals(2, countMax1Streak(0b11));
assertEquals(3, countMax1Streak(0b1110011));
assertEquals(3, countMax1Streak(0b1100111));
assertEquals(3, countMax1Streak(0b1110111));
assertEquals(7, countMax1Streak(0b1111111));
assertEquals(32, countMax1Streak(-1));
You can also use to count the maximum 0 streak like so:
public int countMax0Streak(int value) {
return countMax1Streak(~value);
}
This is an interesting problem. Here is a solution that is generic and also considers all the long values possible (your solution may not work for negative number if you check for the value of n) in Java:
public class LongestBitStreak {
/**
* Returns the longest <i>streak</i> of the given bit b in
given number n.
* A bit streak is defined as a consecutive sequence of the given bit.
* #param n the number to find streak in
* #param b the bit whose streak is to be found
* #return the <i>longest</i> bit streak
*/
static int get(long n, int b) {
if (b != 0 && b != 1)
throw new IllegalArgumentException("second arg: (" + b + ") must be 0 or 1");
int streak = 0, maxStreak = 0;
for (int i = 0; i < 64; i++) {
if ((n & 1) == b) {
streak += 1;
maxStreak = Math.max(streak, maxStreak);
} else {
streak = 0;
}
n >>= 1;
}
return maxStreak;
}
}
Here's an interesting unit test:
#Test
public void foolProof() {
long n = 0b11111000001111100110101010;
long nc = ~n; // One's complement of n
System.out.println(get(n, 1));
System.out.println(get(nc, 0));
assertEquals(get(n, 1), get(nc, 0));
assertEquals(get(n, 0), get(nc, 1));
}
Note that some optimizations are possible based on the values of number and bit, but this should be a decent solution for starters.
Can anyone explain to me how to reverse an integer without using array or String. I got this code from online, but not really understand why + input % 10 and divide again.
while (input != 0) {
reversedNum = reversedNum * 10 + input % 10;
input = input / 10;
}
And how to do use this sample code to reverse only odd number. Example I got this input 12345, then it will reverse the odd number to output 531.
Java reverse an int value - Principles
Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4
Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50
Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7
Java reverse an int value - Pseudocode:
a. Extract off the rightmost digit of your input number. (1234 % 10) = 4
b. Take that digit (4) and add it into a new reversedNum.
c. Multiply reversedNum by 10 (4 * 10) = 40, this exposes a zero to the right of your (4).
d. Divide the input by 10, (removing the rightmost digit). (1234 / 10) = 123
e. Repeat at step a with 123
Java reverse an int value - Working code
public int reverseInt(int input) {
long reversedNum = 0;
long input_long = input;
while (input_long != 0) {
reversedNum = reversedNum * 10 + input_long % 10;
input_long = input_long / 10;
}
if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
return (int) reversedNum;
}
You will never do anything like this in the real work-world. However, the process by which you use to solve it without help is what separates people who can solve problems from the ones who want to, but can't unless they are spoon fed by nice people on the blogoblags.
I am not clear about your Odd number.
The way this code works is (it is not a Java specific algorithm)
Eg.
input =2345
first time in the while loop
rev=5 input=234
second time
rev=5*10+4=54 input=23
third time
rev=54*10+3 input=2
fourth time
rev=543*10+2 input=0
So the reversed number is 5432.
If you just want only the odd numbers in the reversed number then.
The code is:
while (input != 0) {
last_digit = input % 10;
if (last_digit % 2 != 0) {
reversedNum = reversedNum * 10 + last_digit;
}
input = input / 10;
}
Simply you can use this
public int getReverseInt(int value) {
int resultNumber = 0;
for (int i = value; i !=0; i /= 10) {
resultNumber = resultNumber * 10 + i % 10;
}
return resultNumber;
}
You can use this method with the given value which you want revers.
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
That is the solution I used for this problem, and it works fine.
More details:
num % 10
This statement will get you the last digit from the original number.
num /= 10
This statement will eliminate the last digit from the original number, and hence we are sure that while loop will terminate.
rev = rev * 10 + num % 10
Here rev*10 will shift the value by left and then add the last digit from the original.
If the original number was 1258, and in the middle of the run time we have rev = 85, num = 12 so:
num%10 = 2
rev*10 = 850
rev*10 + num%10 = 852
int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());
import java.util.Scanner;
public class Reverse_order_integer {
private static Scanner scan;
public static void main(String[] args) {
System.out.println("\t\t\tEnter Number which you want to reverse.\n");
scan = new Scanner(System.in);
int number = scan.nextInt();
int rev_number = reverse(number);
System.out.println("\t\t\tYour reverse Number is = \"" + rev_number
+ "\".\n");
}
private static int reverse(int number) {
int backup = number;
int count = 0;
while (number != 0) {
number = number / 10;
count++;
}
number = backup;
int sum = 0;
for (int i = count; i > 0; i--) {
int sum10 = 1;
int last = number % 10;
for (int j = 1; j < i; j++) {
sum10 = sum10 * 10;
}
sum = sum + (last * sum10);
number = number / 10;
}
return sum;
}
}
See to get the last digit of any number we divide it by 10 so we either achieve zero or a digit which is placed on last and when we do this continuously we get the whole number as an integer reversed.
int number=8989,last_num,sum=0;
while(number>0){
last_num=number%10; // this will give 8989%10=9
number/=10; // now we have 9 in last and now num/ by 10= 898
sum=sum*10+last_number; // sum=0*10+9=9;
}
// last_num=9. number= 898. sum=9
// last_num=8. number =89. sum=9*10+8= 98
// last_num=9. number=8. sum=98*10+9=989
// last_num=8. number=0. sum=989*10+8=9898
// hence completed
System.out.println("Reverse is"+sum);
public static void main(String args[]) {
int n = 0, res = 0, n1 = 0, rev = 0;
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter No.: ");
n1 = scan.nextInt(); // String s1=String.valueOf(n1);
int len = (n1 == 0) ? 1 : (int) Math.log10(n1) + 1;
while (n1 > 0) {
rev = res * ((int) Math.pow(10, len));
res = n1 % 10;
n1 = n1 / 10;
// sum+=res; //sum=sum+res;
sum += rev;
len--;
}
// System.out.println("sum No: " + sum);
System.out.println("sum No: " + (sum + res));
}
This will return reverse of integer
Just to add on, in the hope to make the solution more complete.
The logic by #sheki already gave the correct way of reversing an integer in Java. If you assume the input you use and the result you get always fall within the range [-2147483648, 2147483647], you should be safe to use the codes by #sheki. Otherwise, it'll be a good practice to catch the exception.
Java 8 introduced the methods addExact, subtractExact, multiplyExact and toIntExact. These methods will throw ArithmeticException upon overflow. Therefore, you can use the below implementation to implement a clean and a bit safer method to reverse an integer. Generally we can use the mentioned methods to do mathematical calculation and explicitly handle overflow issue, which is always recommended if there's a possibility of overflow in the actual usage.
public int reverse(int x) {
int result = 0;
while (x != 0){
try {
result = Math.multiplyExact(result, 10);
result = Math.addExact(result, x % 10);
x /= 10;
} catch (ArithmeticException e) {
result = 0; // Exception handling
break;
}
}
return result;
}
Java solution without the loop. Faster response.
int numberToReverse;//your number
StringBuilder sb=new StringBuilder();
sb.append(numberToReverse);
sb=sb.reverse();
String intermediateString=sb.toString();
int reversedNumber=Integer.parseInt(intermediateString);
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class intreverse
{
public static void main(String...a)throws Exception
{
int no;
int rev = 0;
System.out.println("Enter The no to be reversed");
InputStreamReader str=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(str);
no=Integer.parseInt(br.readLine().toString());
while(no!=0)
{
rev=rev*10+no%10;
no=no/10;
}
System.out.println(rev);
}
}
public static int reverse(int x) {
boolean negetive = false;
if (x < 0) {
x = Math.abs(x);
negative = true;
}
int y = 0, i = 0;
while (x > 0) {
if (i > 0) {
y *= 10;
}
y += x % 10;
x = x / 10;
i++;
}
return negative ? -y : y;
}
Here is a complete solution(returns 0 if number is overflown):
public int reverse(int x) {
boolean flag = false;
// Helpful to check if int is within range of "int"
long num = x;
// if the number is negative then turn the flag on.
if(x < 0) {
flag = true;
num = 0 - num;
}
// used for the result.
long result = 0;
// continue dividing till number is greater than 0
while(num > 0) {
result = result*10 + num%10;
num= num/10;
}
if(flag) {
result = 0 - result;
}
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return 0;
}
return (int) result;
}
Scanner input = new Scanner(System.in);
System.out.print("Enter number :");
int num = input.nextInt();
System.out.print("Reverse number :");
int value;
while( num > 0){
value = num % 10;
num /= 10;
System.out.print(value); //value = Reverse
}
int convert (int n)
{
long val = 0;
if(n==0)
return 0;
for(int i = 1; n > exponent(10, (i-1)); i++)
{
int mod = n%( (exponent(10, i))) ;
int index = mod / (exponent(10, i-1));
val *= 10;
val += index;
}
if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE)
{
throw new IllegalArgumentException
(val + " cannot be cast to int without changing its value.");
}
return (int) val;
}
static int exponent(int m, int n)
{
if(n < 0)
return 0;
if(0 == n)
return 1;
return (m * exponent(m, n-1));
}
It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.
if((inputNum <= 999999999)&&(inputNum > 0 ))
{
System.out.print("Your number reversed is: ");
do
{
endInt = inputNum % 10; //to get the last digit of the number
inputNum /= 10;
system.out.print(endInt);
}
While(inputNum != 0);
System.out.println("");
}
else
System.out.println("You used an incorrect number of integers.\n");
System.out.println("Program end");
Even if negative integer is passed then it will give the negative integer
Try This...
public int reverse(int result) {
long newNum=0,old=result;
result=(result>0) ? result:(0-result);
while(result!=0){
newNum*=10;
newNum+=result%10;
result/=10;
if(newNum>Integer.MAX_VALUE||newNum<Integer.MIN_VALUE)
return 0;
}
if(old > 0)
return (int)newNum;
else if(old < 0)
return (int)(newNum*-1);
else
return 0;
}
This is the shortest code to reverse an integer
int i=5263;
System.out.println(Integer.parseInt(new StringBuffer(String.valueOf(i) ).reverse().toString()));
123 maps to 321, which can be calculated as 3*(10^2)+2*(10^1)+1
Two functions are used to calculate (10^N). The first function calculates the value of N. The second function calculates the value for ten to power N.
Function<Integer, Integer> powerN = x -> Double.valueOf(Math.log10(x)).intValue();
Function<Integer, Integer> ten2powerN = y -> Double.valueOf(Math.pow(10, y)).intValue();
// 123 => 321= 3*10^2 + 2*10 + 1
public int reverse(int number) {
if (number < 10) {
return number;
} else {
return (number % 10) * powerN.andThen(ten2powerN).apply(number) + reverse(number / 10);
}
}
If the idea is not to use arrays or string, reversing an integer has to be done by reading the digits of a number from the end one at a time. Below explanation is provided in detail to help the novice.
pseudocode :
lets start with reversed_number = 0 and some value for original_number which needs to be reversed.
the_last_digit = original_number % 10 (i.e, the reminder after dividing by 10)
original_number = original_number/10 (since we already have the last digit, remove the last digit from the original_number)
reversed_number = reversed_number * 10 + last_digit (multiply the reversed_number with 10, so as to add the last_digit to it)
repeat steps 2 to 4, till the original_number becomes 0. When original_number = 0, reversed_number would have the reverse of the original_number.
More info on step 4: If you are provided with a digit at a time, and asked to append it at the end of a number, how would you do it - by moving the original number one place to the left so as to accommodate the new digit. If number 23 has to become 234, you multiply 23 with 10 and then add 4.
234 = 23x10 + 4;
Code:
public static int reverseInt(int original_number) {
int reversed_number = 0;
while (original_number > 0) {
int last_digit = original_number % 10;
original_number = original_number / 10;
reversed_number = reversed_number * 10 + last_digit;
}
return reversed_number;
}
It is an outdated question, but as a reference for others
First of all reversedNum must be initialized to 0;
input%10 is used to get the last digit from input
input/10 is used to get rid of the last digit from input, which you have added to the reversedNum
Let's say input was 135
135 % 10 is 5
Since reversed number was initialized to 0
now reversedNum will be 5
Then we get rid of 5 by dividing 135 by 10
Now input will be just 13
Your code loops through these steps until all digits are added to the reversed number or in other words untill input becomes 0.
while (input != 0) {
reversedNum = reversedNum * 10 + input % 10;
input = input / 10;
}
let a number be 168,
+ input % 10 returns last digit as reminder i.e. 8 but next time it should return 6,hence number must be reduced to 16 from 168, as divide 168 by 10 that results to 16 instead of 16.8 as variable input is supposed to be integer type in the above program.
If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ;
then put your logic like
Scanner input = new Scanner (System.in);
System.out.println("Enter number to reverse ");
int org = input.nextInt();
int getReminder;
int r = 0;
int count = 0;
while (org !=0){
getReminder = org%10;
r = 10 * r + getReminder;
org = org/10;
}
System.out.println(r);
}
A method to get the greatest power of ten smaller or equal to an integer: (in recursion)
public static int powerOfTen(int n) {
if ( n < 10)
return 1;
else
return 10 * powerOfTen(n/10);
}
The method to reverse the actual integer:(in recursion)
public static int reverseInteger(int i) {
if (i / 10 < 1)
return i ;
else
return i%10*powerOfTen(i) + reverseInteger(i/10);
}
You can use recursion to solve this.
first get the length of an integer number by using following recursive function.
int Length(int num,int count){
if(num==0){
return count;
}
else{
count++;
return Lenght(num/10,count);
}
}
and then you can simply multiply remainder of a number by 10^(Length of integer - 1).
int ReturnReverse(int num,int Length,int reverse){
if(Length!=0){
reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
return ReturnReverse(num/10,Length-1,reverse);
}
return reverse;
}
The whole Source Code :
import java.util.Scanner;
public class ReverseNumbers {
int Length(int num, int count) {
if (num == 0) {
return count;
} else {
return Length(num / 10, count + 1);
}
}
int ReturnReverse(int num, int Length, int reverse) {
if (Length != 0) {
reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
return ReturnReverse(num / 10, Length - 1, reverse);
}
return reverse;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
ReverseNumbers reverseNumbers = new ReverseNumbers();
reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));
scanner.close();
}
}
public int getReverseNumber(int number)
{
int reminder = 0, result = 0;
while (number !=0)
{
if (number >= 10 || number <= -10)
{
reminder = number % 10;
result = result + reminder;
result = result * 10;
number = number / 10;
}
else
{
result = result + number;
number /= 10;
}
}
return result;
}
// The above code will work for negative numbers also
Reversing integer
int n, reverse = 0;
Scanner in = new Scanner(System.in);
n = in.nextInt();
while(n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println("Reverse of the number is " + reverse);
public static int reverseInt(int i) {
int reservedInt = 0;
try{
String s = String.valueOf(i);
String reversed = reverseWithStringBuilder(s);
reservedInt = Integer.parseInt(reversed);
}catch (NumberFormatException e){
System.out.println("exception caught was " + e.getMessage());
}
return reservedInt;
}
public static String reverseWithStringBuilder(String str) {
System.out.println(str);
StringBuilder sb = new StringBuilder(str);
StringBuilder reversed = sb.reverse();
return reversed.toString();
}
public static int reverse(int x) {
int tmp = x;
int oct = 0;
int res = 0;
while (true) {
oct = tmp % 10;
tmp = tmp / 10;
res = (res+oct)*10;
if ((tmp/10) == 0) {
res = res+tmp;
return res;
}
}
}
public static double reverse(int num)
{
double num1 = num;
double ret = 0;
double counter = 0;
while (num1 > 1)
{
counter++;
num1 = num1/10;
}
while(counter >= 0)
{
int lastdigit = num%10;
ret += Math.pow(10, counter-1) * lastdigit;
num = num/10;
counter--;
}
return ret;
}
I am trying to create a program to validate 10 to 12 digit long number sequences based on the luhn algorithm, but my program keeps on telling me that every number is invalid even though they're not.
This number should be valid, but my code doesn't think so: 8112189876
This number should not be valid, which my program agrees with, as it thinks every number is invalid: 8112189875
Here is my code:
static void luhn(){
System.out.print("Enter number to validate:\n");
String pnr = input.nextLine();
int length = pnr.length();
int sum = 0;
for (int i = 1, pos = length - 1; i < 10; i++, pos--){
char tmp = pnr.charAt(pos);
int num = tmp - 0
int product;
if (i % 2 != 0){
product = num * 1;
}
else{
product = num * 2;
}
if (product > 9)
product -= 9;
sum+= product;
boolean valid = (sum % 10 == 0);
if (valid){
System.out.print("Valid!\r");
}
else{
System.out.print("Invalid!");
}
}
}
use org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(number)
Maven Dependency:
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.5.1</version>
</dependency>
The first thing I see is that you have:
int num = tmp - 0
You should instead have:
int num = tmp - '0';
Secondly, you should be validating your sum outside of the for loop, because you only care about the sum after processing all the digits.
Thirdly, you are starting from the end of the number, and you are not including the first number of your string. Why not use i for both tasks?
Resulting (working) method:
static void luhn(){
System.out.print("Enter number to validate:\n");
String pnr = input.nextLine();
// this only works if you are certain all input will be at least 10 characters
int extraChars = pnr.length() - 10;
if (extraChars < 0) {
throw new IllegalArgumentException("Number length must be at least 10 characters!");
}
pnr = pnr.substring(extraChars, 10 + extraChars);
int sum = 0;
// #3: removed pos
for (int i = 0; i < pnr.length(); i++){
char tmp = pnr.charAt(i);
// #1: fixed the '0' problem
int num = tmp - '0';
int product;
if (i % 2 != 0){
product = num * 1;
}
else{
product = num * 2;
}
if (product > 9)
product -= 9;
sum+= product;
}
// #2: moved check outside for loop
boolean valid = (sum % 10 == 0);
if (valid){
System.out.print("Valid!\r");
}
else{
System.out.print("Invalid!");
}
}
Stylistically, this method would be more useful if, instead of method signature
static void luhn() {
it instead had method signature
static boolean luhn(String input) {
This easily allows your code to get the String from ANY source (a file, hardcoded, etc.) and do anything with the result (print a message as yours does, or do something else). Obviously you would move the System.out.print, input.nextLine(), and if(valid) bits of code outside of this method.
Full refactored program:
import java.util.Scanner;
public class Luhn {
private static Scanner input;
public static void main(String... args) {
input = new Scanner(System.in);
System.out.print("Enter number to validate:\n");
String pnr = input.nextLine();
boolean result = luhn(pnr);
printMessage(result);
input.close();
}
static boolean luhn(String pnr){
// this only works if you are certain all input will be at least 10 characters
int extraChars = pnr.length() - 10;
if (extraChars < 0) {
throw new IllegalArgumentException("Number length must be at least 10 characters!");
}
pnr = pnr.substring(extraChars, 10 + extraChars);
int sum = 0;
for (int i = 0; i < pnr.length(); i++){
char tmp = pnr.charAt(i);
int num = tmp - '0';
int product;
if (i % 2 != 0){
product = num * 1;
}
else{
product = num * 2;
}
if (product > 9)
product -= 9;
sum+= product;
}
return (sum % 10 == 0);
}
private static void printMessage(boolean valid) {
if (valid){
System.out.print("Valid!\r");
}
else{
System.out.print("Invalid!");
}
}
}
I use this function in an app for checking card number validity :
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
Hope it helps,
If you use Java 10 or higher, you can use the following code:
public static boolean luhn(String s) {
IntUnaryOperator sumDigits = n -> n / 10 + n % 10;
var digits = s.chars()
.map(Character::getNumericValue)
.toArray();
return IntStream.rangeClosed(1, digits.length)
.map(i -> digits.length - i)
.map(i -> i % 2 == 0 ? digits[i] : sumDigits.applyAsInt(digits[i] * 2))
.sum() % 10 == 0;
}
It's the functional approach to this algorithm.
You should be subtracting '0' from tmp, not 0. Subtracting 0 returns the ASCII value, which you don't want.
Here's some functions I wrote to both calculate the check digit for a given number and to verify a given number sequence and extract the number from it.
To calculate the check digit for a given number:
/**
* Generates the check digit for a number using Luhn's algorithm described in detail at the following link:
* https://en.wikipedia.org/wiki/Luhn_algorithm
*
* In short the digit is calculated like so:
* 1. From the rightmost digit moving left, double the value of every second digit. If that value is greater than 9,
* subtract 9 from it.
* 2. Sum all of the digits together
* 3. Multiply the sum by 9 and the check digit will be that value modulo 10.
*
* #param number the number to get the Luhn's check digit for
* #return the check digit for the given number
*/
public static int calculateLuhnsCheckDigit(final long number) {
int sum = 0;
boolean alternate = false;
String digits = Long.toString(number);
for (int i = digits.length() - 1; i >= 0; --i) {
int digit = Character.getNumericValue(digits.charAt(i)); // get the digit at the given index
digit = (alternate = !alternate) ? (digit * 2) : digit; // double every other digit
digit = (digit > 9) ? (digit - 9) : digit; // subtract 9 if the value is greater than 9
sum += digit; // add the digit to the sum
}
return (sum * 9) % 10;
}
To verify a sequence of digits using Luhn's algorithm and extract the number:
/**
* Verifies that a given number string is valid according to Luhn's algorithm, which is described in detail here:
* https://en.wikipedia.org/wiki/Luhn_algorithm
*
* In short, validity of the number is determined like so:
* 1. From the rightmost digit (the check digit) moving left, double the value of every second digit. The check
* digit is not doubled; the first digit doubled is the one immediately to the left of the check digit. If that
* value is greater than 9, subtract 9 from it.
* 2. Sum all of the digits together
* 3. If the sum modulo 10 is equal to 0, then the number is valid according to Luhn's algorithm
*
* #param luhnsNumber the number string to verify and extract the number from
* #return an empty Optional if the given string was not valid according to Luhn's algorithm
* an Optional containing the number verified by Luhn's algorithm if the given string passed the check
*/
public static Optional<Long> extractLuhnsNumber(final String luhnsNumber) {
int sum = 0;
boolean alternate = true;
Long number = Long.parseLong(luhnsNumber.substring(0, luhnsNumber.length() - 1));
for (int i = luhnsNumber.length() - 1; i >= 0; --i) {
int digit = Character.getNumericValue(luhnsNumber.charAt(i)); // get the digit at the given index
digit = (alternate = !alternate) ? (digit * 2) : digit; // double every other digit
digit = (digit > 9) ? (digit - 9) : digit; // subtract 9 if the value is greater than 9
sum += digit; // add the digit to the sum
}
return (sum % 10 == 0) ? Optional.of(number) : Optional.empty();
}
Newcomers to this post/question can check appropriate Wikipedia page for solution. Below is the Java code copy-pasted from there.
public class Luhn
{
public static boolean check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
}
package randomNumGen;
public class JavaLuhnAlgorithm {
public static void main(String[] args) {
// TODO Auto-generated method stub
validateCreditCardNumber("8112189876");
String imei = "012850003580200";
validateCreditCardNumber(imei);
}
private static void validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
System.out.println(str + " is a valid credit card number");
} else {
System.out.println(str + " is an invalid credit card number");
}
}
}