Java Program to Reverse a Number

Introduction

Reversing a number is a common programming task that can be achieved using different approaches in Java. This guide will show you how to reverse a number using various methods, including mathematical operations, string manipulation, and recursion.

Problem Statement

Given an integer, reverse its digits. For example:

  • Input: 12345
  • Output: 54321

Example 1:

  • Input: 6789
  • Output: 9876

Example 2:

  • Input: -123
  • Output: -321

Approach 1: Using Mathematical Operations

  1. Extract the Digits: Use the modulus operator (%) to extract the last digit of the number.
  2. Build the Reversed Number: Multiply the current reversed number by 10 and add the extracted digit.
  3. Repeat: Repeat the process until all digits have been processed.
/**
 * Java Program to Reverse a Number using Mathematical Operations
 * Author: https://www.javaguides.net/
 */
public class ReverseNumberMath {

    public static void main(String[] args) {
        int number = 12345;
        int reversedNumber = 0;

        while (number != 0) {
            int digit = number % 10;  // Extract the last digit
            reversedNumber = reversedNumber * 10 + digit;  // Build the reversed number
            number /= 10;  // Remove the last digit
        }

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

Output

For the input 12345, the output will be:

Reversed Number: 54321

Explanation

  • This method uses a loop to extract each digit of the number and construct the reversed number by adding the extracted digit to the current reversed number multiplied by 10.

Approach 2: Using StringBuilder

  1. Convert the Number to a String: Convert the number to a string.
  2. Reverse the String: Use StringBuilder to reverse the string.
  3. Convert Back to a Number: Convert the reversed string back to an integer.
/**
 * Java Program to Reverse a Number using StringBuilder
 * Author: https://www.javaguides.net/
 */
public class ReverseNumberStringBuilder {

    public static void main(String[] args) {
        int number = 12345;

        // Convert number to String and then to StringBuilder
        StringBuilder sb = new StringBuilder(String.valueOf(number));
        
        // Reverse the string
        String reversedString = sb.reverse().toString();
        
        // Convert the reversed string back to an integer
        int reversedNumber = Integer.parseInt(reversedString);

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

Output

For the input 12345, the output will be:

Reversed Number: 54321

Explanation

  • This approach converts the number to a string, reverses the string using StringBuilder, and then converts the reversed string back to an integer.

Approach 3: Using Recursion

  1. Recursive Function: Create a recursive function to reverse the digits of the number.
  2. Base Case: If the number is 0, return 0.
  3. Recursive Step: Extract the last digit and call the function recursively with the rest of the digits.
/**
 * Java Program to Reverse a Number using Recursion
 * Author: https://www.javaguides.net/
 */
public class ReverseNumberRecursion {

    public static void main(String[] args) {
        int number = 12345;
        int reversedNumber = reverseNumber(number, 0);
        System.out.println("Reversed Number: " + reversedNumber);
    }

    // Recursive function to reverse the number
    public static int reverseNumber(int number, int reversed) {
        if (number == 0) {
            return reversed;
        }
        int digit = number % 10;
        reversed = reversed * 10 + digit;
        return reverseNumber(number / 10, reversed);
    }
}

Output

For the input 12345, the output will be:

Reversed Number: 54321

Explanation

  • The recursive method repeatedly extracts the last digit of the number and calls itself with the remaining digits until the number is fully reversed.

Conclusion

These three approaches show how to reverse a number in Java using different techniques. The mathematical approach is more traditional and efficient, while the StringBuilder approach is straightforward and leverages Java's built-in string manipulation features. The recursive approach provides a more functional programming style solution. Each method is effective, and the choice depends on your specific needs and preferences.

Related Java Programs with Output

  1. Java Program to Find Factorial Using Recursion
  2. Java Program to Find Sum of Natural Numbers
  3. Java Program to Reverse a Number
  4. Java Program to Find Prime Numbers
  5. Java Program to Check Armstrong Number
  6. Java Program to Count the Number of Digits in a Number
  7. Java Program for Prime Numbers Within a Range
  8. Java Program to Find the Largest of Three Numbers
  9. Java Program to Check if a Number is Prime
  10. Java Program to Find the Fibonacci Series
  11. Java Program to Check if a Number is Positive or Negative
  12. Java Program to Find GCD of Two Numbers
  13. Java Program to Find Strong Number
  14. Java Program to Find LCM of Two Numbers
  15. Java Program to Check Palindrome Number
  16. Java Program to Swap Two Numbers Without Using a Temp Variable
  17. Java Program to Find the Second Largest Number in an Array
  18. Java Program to Find GCD of Two Numbers
  19. Java Program to Find Strong Number
  20. Java Program to Find LCM of Two Numbers
  21. Java Program to Check Palindrome Number
  22. Java Program to Find the Largest of Three Numbers
  23. Java Program to Check if a Number is Prime
  24. Java Program to Swap Two Numbers Without Using a Temp Variable
  25. Java Program to Find the Second Largest Number in an Array
  26. Java Program to Check if a Given Number is Perfect Square
  27. Java Program to Find the Fibonacci Series
  28. Java Program to Check if a Number is Positive or Negative

Comments