Turn It Around: Reversing a Number in Java

Hey, Java explorers! Today, we’re going to learn an interesting and common problem-solving exercise: reversing a number in Java. It might seem like a simple task, but it can be quite intriguing, especially for newcomers to the language. So, let’s get cracking and see how we can reverse a number in Java!

Reversing a Number in Java

The idea to reverse a number is simple: we use modulo and division operations to peel off the last digit of the number and build our reversed number. Here’s a simple method to reverse a number:

public static int reverseNumber(int num) {
    int reversed = 0;

    while (num != 0) {
        int digit = num % 10;
        reversed = reversed * 10 + digit;
        num /= 10;
    }

    return reversed;
}

In this method, we first initialise our reversed number to 0. Then, we enter a loop that continues until num becomes 0. In each iteration, we extract the last digit of num using the modulo operation, add it to the end of reversed, and then remove the last digit from num using integer division.

Example

Let’s test our reverseNumber method with a sample number:

public static void main(String[] args) {
    int number = 12345;
    int reversed = reverseNumber(number);
    System.out.println("The reversed number is: " + reversed);
}

Output

The reversed number is: 54321

Our reverseNumber method successfully reversed the number!

Final Note

In this blog post, we’ve seen how to reverse a number in Java. By using a while loop, the modulo operation, and integer division, we’ve crafted a simple yet efficient method to turn a number around. It’s another example of how basic mathematics can solve problems in programming. Happy coding, and see you in the next post!

📚 Further Reading & Related Topics

If you’re exploring number manipulation and algorithmic problem-solving in Java, these related articles will provide deeper insights:

• How to Swap Two Numbers Without Using a Temp Variable in Java – Learn another fundamental number manipulation technique using arithmetic operations.

• Write a Java Program to Check if a Number is Prime or Not – Explore a common mathematical problem that reinforces algorithmic thinking and logic implementation in Java.

Leave a comment

I’m Sean

Welcome to the Scalable Human blog. Just a software engineer writing about algo trading, AI, and books. I learn in public, use AI tools extensively, and share what works. Educational purposes only – not financial advice.

Let’s connect