How to reverse a number in Java accepted by user and add both reversed number -
i have written code reverse number in java. taking 1 character/displaying it.
import java.util.scanner; class helloworld { public static void main(string args[]) { int n,n1, reverse = 0,rev = 0; system.out.println("enter number reverse"); scanner scanner = new scanner(system.in); system.err.println("please enter first number reverse : "); int number = scanner.nextint(); system.out.println("enter second number reverse :"); int num = scanner.nextint(); if( number >0) { reverse = reverse * 10; reverse = reverse + number%10; number = number/10; if(num>0) { rev = rev * 10; rev = rev + num%10; num = num/10; } } system.out.println("reverse of entered number "+reverse); system.out.println("reverse of entered number "+rev); } }
input1 -65 output displayed - 5 input2 -34 output displayed - 4
i have reverse user accpeted inputs , add reverse of both boths inputs.
you can , @user7 pointed out, use while loop , instead of if loop
while( number >0) { reverse1 = reverse1 * 10; reverse1 = reverse1 + number%10; number = number/10; } while( number2 >0) { reverse2 = reverse2 * 10; reverse2 = reverse2 + num%10; num = num/10; } system.out.println(reverse1+reverse2);
now multiple numbers
int[] numbers= numbers reversed; reversesum=0; for(int i=0;i<numbers.length;i++){ reversesum+= reverse(numbers[i]); } ... public int reverse(int number){ while( number >0) { reverse = reverse * 10; reverse = reverse + number%10; number = number/10; } return reverse; }
hope helps!
good luck!
Comments
Post a Comment