views:

120

answers:

2

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;   
}
+3  A: 

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; 
}
sheki
theres a mistake in your code. It should be `reversedNum = reversedNum * 10 + input % 10;`
Faisal Feroz
It will loop infinite?
Now it is proper I assume. The input=input/10 will take care and there will be no infinite loop.
sheki
+1  A: 
public int reverseNumber(int number)
{
  int reversedNumber = 0;
  while(number != 0)
  {
     reversedNumber = (reversedNumber * 10) + (number % 10);
     number /= 10;
  }
  return reversedNumber;
} 
org.life.java