Home  >  Article  >  Java  >  How to Reverse Only Odd Numbers in an Integer in Java?

How to Reverse Only Odd Numbers in an Integer in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 17:31:03471browse

How to Reverse Only Odd Numbers in an Integer in Java?

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:

  • ReversedNum Multiplication: The variable reversedNum is initially set to 0. In each iteration of the loop, we multiply reversedNum by 10 to "shift" the existing reversed number one digit to the left.
  • Input Modding: We calculate input % 10 to extract the rightmost digit of the input number. This gives us the digit to be added to the reversed number.
  • Adding to ReversedNum: The extracted rightmost digit is added to reversedNum to form the reversed number.
  • Division of Input: Finally, we divide the input number by 10 to remove the rightmost digit and continue the process with the remaining digits.

Reversing Only Odd Numbers:

To reverse only odd numbers in a given integer, you can use the following steps:

  • Separate the even and odd digits into different variables.
  • Reverse the odd digits using the above method.
  • Combine the reversed odd digits with the original even digits.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn