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.
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.
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.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.
This will return reverse of integer
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.
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.