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.
Simply you can use this
You can use this method with given value which you want revers.
I used
String
and I converted initially theint
toString
.Then I used the reverse method. I found the reverse of the number inString
and then I converted the string back toint
. Here is the program.That is the solution I used for this problem, and it works fine. More details:
This statement will get you the last digit from the original number.
This statement will eliminate the last digit from the original number, and hence we are sure that while loop will terminate.
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