Reverse an Integer Without Arrays in Java
Your query concerns reversing an integer without recourse to arrays or strings. You encounter difficulties understanding the rationale behind the following code snippet:
while (input != 0) { reversedNum = reversedNum * 10 + input % 10; input = input / 10; }
Principles of Integer Reversal
To grasp the logic behind this algorithm, consider the following concepts:
Pseudocode
The reversal algorithm follows these steps:
Working Code
Here is an updated version of the provided code that accommodates large input integers and handles possible overflow:
<code class="java">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; }
Reverse Odd Numbers Only
To reverse only odd digits in an integer, you can implement the same algorithm but add a conditional statement to skip over even digits. For example:
public int reverseOddDigits(int input) { long reversedNum = 0; long input_long = input; while (input_long != 0) { if (input_long % 2 == 1) { 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; }</code>
With this modified code, you can now selectively reverse the odd digits in your input integer.
The above is the detailed content of How does the provided Java code reverse an integer without using arrays or strings?. For more information, please follow other related articles on the PHP Chinese website!