Java: Reverse Integer Without Using Array
This article explores how to reverse an integer in Java without resorting to arrays, using a concise algorithm.
Algorithm
The algorithm leverages the modulus (%) operator to extract the rightmost digit of the input integer. This digit is appended to a new variable, reversedNum.
Next, reversedNum is multiplied by 10 to create a vacant position at the right end. Simultaneously, the input integer is divided by 10 to remove the extracted digit.
The process is repeated until the input integer reaches zero.
Here's a step-by-step breakdown:
Code Example:
<code class="java">while (input != 0) { reversedNum = reversedNum * 10 + input % 10; input = input / 10; }</code>
Reversing Odd Digits Only
To reverse odd digits only, extract every second digit using the modulus operator and shift it to the left by multiplying it by 10. Here's a sample code:
<code class="java">int reversedOdd = 0; while (input > 0) { reversedOdd = reversedOdd * 100 + input % 100; input = input / 100; }</code>
The above is the detailed content of How to Reverse an Integer in Java Without Using Arrays?. For more information, please follow other related articles on the PHP Chinese website!