Skip to content
ADevGuide
Go back

Reverse An Integer In Java 8 – Simple Code Example

Reverse An Integer In Java 8 – Simple Code Example

Reverse An Integer In Java

Reverse an Integer in Java is a part of our Java code examples series. This is a very common question for junior level java developers.

Interview Problem Statement

20 Java Regular Expressions Quiz Regex Questions [MCQ]

Code Example

package com.adevguide.java.problems;

public class ReverseInteger {

public static void main(String\[\] args) {
    // Variable to hold input value
    Integer input = 123;
    // Variable to hold reversed value
    Integer reverse = 0;
    // loop till input value becomes zero
    while (input != 0) {
        // multiple previous reverse value by 10 , add the remainder to it and save it back
        // in reverse variable
        reverse = reverse \* 10 + input % 10;
        // Divide input by 10 and store quotient value in input
        input = input / 10;
    }
    // Print reverse Value
    System.out.println("Reverse Integer ::" + reverse);
}

}

Code Explanation

To reverse an integer in Java, we will follow the following steps:

  1. Find one’s place of the input and add it to 10 x previously calculated reverse value.
  2. Change input value to the quotient of division of input by 10.

Example:

Input = 123

Iteration 1:

reverse = 0 * 10 + 123 % 10

reverse = 3

Input = 12

Iteration 2:

reverse = 3 * 10 + 12 % 10

reverse = 32

Input = 1

Iteration 3:

reverse = 32 * 10 + 1 % 10

reverse = 321

Input = 0

Source Code

As always, you can find all our source code at GitHub.

GitHub Link


Share this post on:

Previous Post
Most Important Spring Boot Interview Questions [2020]
Next Post
Builder Design Pattern Java Real World Example