TeachingBee

How To Reverse A Number In Java

Reverse A Number In Java

In this article, we will see how to reverse a number in Java.

Let’s dive in.

Problem Statement

Reversing a number means swapping the digits. To Reverse a number we convert a number from its original form to a form where its digits are in the opposite order.

For Example:

Input:

96724

Output:

42769

Solution

We will see three different ways to reverse a number in Java. Those are:

  1. Using Loops
  2. Using Recursion
  3. Using StringBuilder

Approach 1: Using Loops

Let’s check how to reverse a number in java using loops

Algorithm

You can represent any number by using the format 10*a+b, and we will utilize this representation to reverse a number.

  • Begin with your original number (num).
  • Initialise an empty result variable (rev = 0).
  • Until num is not 0:
    • Extract the last digit of ‘num’ using the modulo operator (num % 10).
    • To form rev we will use 10*a+b
    • So, Multiply rev by 10 and add the last digit obtained to rev.
    • Divide num by 10 (discard the remainder) to move to the next digit.
  • Once num is 0, rev will have the reversed number.

Java Program To Reverse A Number Using Loops

// Java Program To Reverse A Number Using Loops

public class ReverseNumber {
    public static void main(String[] args) {
        int num = 12345; // Replace this with the number you want to reverse
        int rev = 0;

        while (num != 0) {
            int digit = num % 10; // Extract the last digit
            rev = rev * 10 + digit; // Add the digit to the reversed number
            num /= 10; // Remove the last digit
        }

        System.out.println("Reversed Number: " + rev);
    }
}

Output

Reversed Number: 54321

Code Explanation

StepnumrevAction
1123450Initialize num and rev.
2123455Extract last digit (12345 % 10 = 5).
Add the digit to the reversed number (0*10 + 5)
12345Remove last digit (num /= 10).
3123454Extract last digit (1234 % 10 = 4).
Add the digit to the reversed number (5*10 + 4)
12354Remove last digit (num /= 10).
4123543Extract last digit (123 % 10 = 3).
Add the digit to the reversed number (54*10 + 3)
12543Remove last digit (num /= 10).
5125432Extract last digit (12 % 10 = 2).
Add the digit to the reversed number (543*10 + 2)
15432Remove last digit (num /= 10).
6154321Extract last digit (1 % 10 = 1).
Add the digit to the reversed number (5432*10 + 1)
054321Remove last digit (num /= 10).
7054321The loop exits since num is now 0.
Reverse a number in java using Loops

At the end of the program, rev contains the reversed number, which is 54321.

Approach 2: Using Recursion

The above solution using loop is a iterative way of solving the problem. Let’s check how to reverse a number in java using recursion.

Algorithm

The approach will be similar to previous loop solution.But instead of looping, we will make recursive call to the function. The algorithm is as follows:

  • Start with your original number, ‘num.’
  • Initialize an empty variable called ‘rev’ to store the reversed number (rev = 0).
  • Create a recursive function, ‘reverseRecursive,’ that takes ‘num‘ and ‘rev‘ as parameters.
  • In the recursive function:
    • Base Case:
      • If num = 0, return ‘rev’ as the reversed number because there are no more digits to reverse.
    • Recursive Step:
      • Extract the last digit of ‘num’ using the modulo operator (num % 10).
      • To build ‘rev,’ multiply the current ‘rev’ by 10 and then add the last digit obtained (10*rev + last_digit_of_num).
      • Proceed to the next digit by dividing ‘num’ by 10 (disregard the remainder).
      • Make a recursive call to ‘reverseRecursive’ with the updated ‘num’ and ‘rev.’
  • In the main program, call the ‘reverseRecursive’ function with the original number ‘num‘ and the initial ‘rev’ value of 0.
  • The final reversed number will be the result.

Java Program To Reverse A Number Using Recursion

// Java Program To Reverse A Number Using Recursion

public class ReverseNumberRecursion {
    public static int reverseRecursive(int num, int rev) {
        // Base case: If num is 0, return the reversed number (rev)
        if (num == 0) {
            return rev;
        }

        // Extract the last digit of num
        int lastDigit = num % 10;

        // Build 'rev' by multiplying it by 10 and adding the last digit
        rev = rev * 10 + lastDigit;

        // Proceed to the next digit by dividing 'num' by 10
        num /= 10;

        // Make a recursive call with the updated 'num' and 'rev'
        return reverseRecursive(num, rev);
    }

    public static void main(String[] args) {
        int num = 12345; // Replace this with the number you want to reverse
        int reversedNum = reverseRecursive(num, 0);

        System.out.println("Reversed Number: " + reversedNum);
    }
}

Output

Reversed Number: 54321

Code Explanation

StepnumrevAction
1123450Initialize num and rev.
2123450Call reverseRecursive(12345, 0).
3123451. Recursive call: extract last digit (12345 % 10 = 5)
2. Update rev to 0 * 10 + 5 = 5
3. Call reverseRecursive(1234, 5).
4123541. Recursive call: extract last digit (1234 % 10 = 4)
2. Update rev to 5 * 10 + 4 = 54
3. Call reverseRecursive(123, 54).
5125431. Recursive call: extract last digit (123 % 10 = 3)
2. Update rev to 54 * 10 + 3 = 543
3. Call reverseRecursive(12, 543).
6154321. Recursive call: extract last digit (12 % 10 = 2)
2. Update rev to 543 * 10 + 2 = 5432
3. Call reverseRecursive(1, 5432).
7054321Recursive call: base case reached (num = 0), return rev (54321).
81234554321In the main program, display “Reversed Number: 54321”.
Reverse a number in java using Recursion

The final reversed number is 54321, as shown in step 8.

Approach 3: Using String builder

Let’s check how to reverse a number in java using String builder

Algorithm

In this approach we will use String to reverse a number in java.

  • Convert the num to a string.
  • Create a StringBuilder object to store the reversed string.
  • Iterate through the characters of the string from right to left.
  • Append each character to the StringBuilder in reverse order.
  • Convert the StringBuilder back to a integer to get the reversed number.

Java Program To Reverse A Number Using StringBuilder

// Java Program To Reverse A Number Using StringBuilder

public class ReverseNumberWithStringBuilder {

    public static void main(String[] args) {

        int num = 12345; // Replace this with the number you want to reverse

        // Step 1: Convert the number to a string
        String numString = Integer.toString(num);

        // Step 2: Create a StringBuilder object to store the reversed string
        StringBuilder reversedBuilder = new StringBuilder();

        // Step 3 and Step 4: Iterate through the characters from right to left and append to StringBuilder
        for (int i = numString.length() - 1; i >= 0; i--) {
            reversedBuilder.append(numString.charAt(i));
        }

        // Step 5: Convert the StringBuilder back to an integer to get the reversed number
        int reversedNum = Integer.parseInt(reversedBuilder.toString());

        System.out.println("Reversed Number: " + reversedNum);
    }
}

Output

Reversed Number: 54321

Code Explanation

StepnumStringreversedBuilderAction
1“12345”EmptyInitialize num and reversedBuilder.
2“12345”EmptyConvert num to a string (numString).
3“12345”EmptyCreate an empty StringBuilder.
4“12345”“5”Append ‘5’ to reversedBuilder.
5“12345”“54”Append ‘4’ to reversedBuilder.
6“12345”“543”Append ‘3’ to reversedBuilder.
7“12345”“5432”Append ‘2’ to reversedBuilder.
8“12345”“54321”Append ‘1’ to reversedBuilder.
9“12345”54321Convert reversedBuilder to a string.
10“12345”54321Convert the reversed string to an integer.
11“12345”54321Display the reversed number (54321).
Reverse a number in java using StringBuilder

The final reversed number is 54321, as shown in step 11.

Space and Time Complexity

MethodTime ComplexitySpace Complexity
Using a LoopO(n)O(1)
Using RecursionO(n)O(n)
Using StringBuilderO(n) (amortized)O(n)
Space and Time Complexity

Note: In the context of these complexities, n represents the number of digits in num, which is equivalent to log10(num).

Key Takeaways

  • Basic approach to reverse a number on extracting digits systematically from the number and reconstructing the reversed number from right to left.
  • Recursive approach also follows similar digit extraction logic, but makes a recursive call repeatedly instead of a loop. Base case is reached when number becomes 0.
  • Converting the number to a String allows leveraging StringBuilder to simply append characters in reverse order. StringBuilder can then be converted back to number.

Similar Posts

Add Days To The Current Date in Java

Calculate Area of Hexagon in Java

Program to Calculate EMI in Java

Calculate Area of a Circle in Java

Leap Year Program In Java

Checkout more Java Tutorials here.

I hope You liked the post ?. For more such posts, ? subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.

FAQ

How do I reverse a negative number in Java?

Can I reverse a floating-point number in Java?

How can I check if a reversed number is a palindrome in Java?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In