Home >Java >javaTutorial >How to Reverse an Integer in Java Without Using Arrays?

How to Reverse an Integer in Java Without Using Arrays?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 00:01:33660browse

How to Reverse an Integer in Java Without Using Arrays?

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:

  1. Extract rightmost digit: (input % 10)
  2. Append digit to reversedNum: reversedNum = reversedNum * 10 (input % 10)
  3. Remove extracted digit from input: input = input / 10
  4. Repeat steps 1-3 until input is zero

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!

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