Java reverse an int value without using array

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; 
}

Leave a Comment