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.
Input : 11 Output : 13 (11)10 = (1011)2. After reversing the bits we get: (1101)2 = (13)10. Input : 10 Output : 5 (10)10 = (1010)2. After reversing the bits we get: (0101)2 = (101)2 = (5)10.
reverse = reverse * 10 + lastDigit; You can see by multiplying a number by 10 you increase the number of digits by 1 and then add the last digit.
Java reverse an int value - Principles
Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4
Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50
Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7
Java reverse an int value - Pseudocode:
a. Extract off the rightmost digit of your input number. (1234 % 10) = 4
b. Take that digit (4) and add it into a new reversedNum.
c. Multiply reversedNum by 10 (4 * 10) = 40, this exposes a zero to the right of your (4).
d. Divide the input by 10, (removing the rightmost digit). (1234 / 10) = 123
e. Repeat at step a with 123
Java reverse an int value - Working code
public int reverseInt(int input) { long reversedNum = 0; long input_long = input; while (input_long != 0) { reversedNum = reversedNum * 10 + input_long % 10; input_long = input_long / 10; } if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) { throw new IllegalArgumentException(); } return (int) reversedNum; }
You will never do anything like this in the real work-world. However, the process by which you use to solve it without help is what separates people who can solve problems from the ones who want to, but can't unless they are spoon fed by nice people on the blogoblags.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With