Java: Reverse an Int Value Without Using Array
Explanation of the Code:
The code snippet you provided uses a while loop to reverse an integer value. Here's how it works:
Reversing Only Odd Numbers:
To reverse only odd numbers in a given integer, you can use the following steps:
Sample Code:
<code class="java">public static int reverseOdd(int input) { int even = 0; int odd = 0; // Separate even and odd digits while (input > 0) { int digit = input % 10; if (digit % 2 == 0) { even = even * 10 + digit; } else { odd = odd * 10 + digit; } input /= 10; } // Reverse odd digits odd = reverseInt(odd); // Combine reversed odd and original even digits return even + odd; } public static int reverseInt(int input) { long reversedNum = 0; long input_long = input; while (input_long != 0) { reversedNum = reversedNum * 10 + input_long % 10; input_long /= 10; } if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) { throw new IllegalArgumentException(); } return (int) reversedNum; }</code>
The above is the detailed content of How to Reverse Only Odd Numbers in an Integer in Java?. For more information, please follow other related articles on the PHP Chinese website!