Friday, September 15, 2023

How to Reverse an Integer in Java without converting to String? Example and Solution

Hello guys, LeetCode has a problem reversing digits of an integer number without using any library method like the reverse() method of StringBuffer. In LeetCode, you can solve this problem with many different languages like Java, C, C++, C#, Python, Ruby, and even JavaScript. Btw, in the article, you will learn how to solve this problem in Java. Before approaching a solution let's first read the problem statement :

Reverse digits of an integer.

Example 1: x = 123, return 321
Example 2: x = -123, return -321

The problem looks simple but it's not simple there are many things you need to consider in order to produce a solution that is accepted by LeetCode, which has thousands of test cases to test your solution.

For example, you need to consider not just a positive integer but also a negative integer. Remember, a positive integer can also be written using the + sign, so you need to handle that as well. If the integer's last digit is 0, what should the output be? I mean, cases such as 10, 100.

If the return type of method is an integer then you can simply return 1, it's perfectly ok, but if the return type of method is String then you may need to return 001 or 0001. For the purpose of this solution, we expect our method to return an integer, so 1 is fine.

By the way, if you are preparing for coding interviews then you should be prepared for such kinds of questions. According to Leetcode, this is one of the common coding problems from Google interviews.




How to Reverse digits of an Integer in Java without converting to String?

Here are my algorithms to solve this problem of reversing integer numbers without using any direct library method. 

The crux of this problem is how to use division and modulo operators in Java to get the last digit of a number and get rid of the last digit as well.

If you remember, I have shared this trick before when I was explaining how to use a modulo operator in Java. This is a really neat trick and will help you to solve many programming problems where you need to divide numbers into individual digits.

When you divide a number by 10, you get rid of the last digit, for example, 211/10 will give you 21, and 21/10 will give you 2, so you got rid of the last 2 digits by dividing your number by 10 twice.

Similarly, you can use the number modulo 10 to get the last digit of the number, for example, 221%10 will return 1, which is the last digit and 22%10 will return 2, which is the last digit of 22. You can apply this logic until you processed the last digit.

How to Reverse digits of an Integer in Java without converting to String?


Now the question comes, how do you arrange those digits in reverse order? Well, you can use just the opposite, I mean, multiplication and addition to creating a new number with digits of the old number in reverse order.  I have used the following logic to assemble digits into reverse order :

reverse = reverse * 10 + lastDigit;

You can see by multiplying a number by 10 you increase the number of digits by 1 and then add the last digit. For negative numbers, we multiply it by -1 to first make it positive and then apply the same logic, while returning numbers we just multiply it by -1 again to convert the reversed number into negative.

This kind of little trick really helps to solve coding problems during interviews and in your day-to-day life. If you want to learn more of such patterns to boost your problem-solving skills then I also suggest you check out Grokking the Coding Interview: Patterns for Coding Questions course on Educative.

best course to learn coding patterns for interviews

This course will teach you 6 essential coding patterns like Sliding Window, Two Pointers, Fast and Slow Pointers, Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve zones of frequently asked coding problems.  This is very good for preparing coding interviews as well as improving your coding skills.


Java Program to reverse an Integer without using String

Here is our complete Java program to reverse a given Integer without using String. As explained in the above paragraph, I have used the Arithmetic and modulus operator to solve this problem.

import java.util.Scanner;

/**
 * Java Program to reverse Integer in Java, number can be negative.
 * Example 1:  x = 123, return 321
 * Example 2:  x = -123, return -321
 *
 * @author Javin Paul
 */

public class ReverseInteger{

    public static void main(String args[]) {
        int input = 5678;
        int output = reverseInteger(5678);
        System.out.println("Input : " + input + " Output : " + output);
    }

    /*
     * Java method to reverse an integer value. there are couple of 
     * corner cases
     * which this method doesn't handle e.g. integer overflow.
     */
    public static int reverseInteger(int number) {
        boolean isNegative = number < 0 ? true : false;
        if(isNegative){
            number = number * -1;
        }
        int reverse = 0;
        int lastDigit = 0;

        while (number >= 1) {
            lastDigit = number % 10; // gives you last digit
            reverse = reverse * 10 + lastDigit;
            number = number / 10; // get rid of last digit
        }

        return isNegative == true? reverse*-1 : reverse;
    }

}

Result :
Input : 5678 Output : 8765

You can see that output is the just reverse of input. The first digit has exchanged position with the last digit, the second with the second last, and so on.

By the way, if you are solving LeetCode problems as part of your interview preparation then you can also see these coding interview preparation courses and Cracking the Coding Interview booktwo of the most useful books and courses for preparing programming job interviews. You will learn more in a short time.



JUnit Tests for Solution of Reverse Integer in Java

Here is my limited set of JUnit tests for checking my solution. It checks for input zero and one, a simple positive number, a negative number, a positive number with a plus sign, and a number ending with zero. Our solution passes all the tests but it's not enough.

If you submit this solution on LeetCode it only managed to pass 1028 out of 1032 test cases. Yes, you read it write, they have 1032 to test this problem, no wonder our solution failed. FYI, it failed for input 1534236469, see if you can spot the bug and fix it.

import org.junit.*;
import static org.junit.Assert.*;
/**
 * JUnit test four our solution to problem of reverse Integer in Java.
 *
 * @author WINDOWS 8
 *
 */
public class ReverseIntegerTest{

    @Test
    public void testZeroAndOne(){
        assertEquals(0, ReverseIntegerTest.reverseInteger(0));
        assertEquals(1, ReverseIntegerTest.reverseInteger(1));      
    }
   
    @Test
    public void testSimple(){
        assertEquals(4321, ReverseIntegerTest.reverseInteger(1234));    
    }
   
    @Test
    public void testNegative(){
        assertEquals(-321, ReverseIntegerTest.reverseInteger(-123));      
    }
   
    @Test
    public void testNumberWithSign(){
        assertEquals(321, ReverseIntegerTest.reverseInteger(+123));
    }
   
    @Test
    public void testNumberEndingWithZero(){
        assertEquals(1, ReverseIntegerTest.reverseInteger(1000));
        assertEquals(1, ReverseIntegerTest.reverseInteger(10));      
    }
   
}

and here is the result of running these JUnit test cases in Eclipse :

How to reverse Integer in Java - Leetcode Solutin JUnit tests

You can see that lovely green bar, which means all five tests are passed.

Hint: Leetcode is OK if your function returns 0 when the reversed integer overflows. Since our code doesn't handle integer overflow like this, I left this as an exercise for you guys to fix.


That's all about how to reverse Integer in Java. By the way, this solution is prone to integer overflow and will not be expected at Leetcode.  It only managed to pass 1028 test cases out of staggering 1032 tests and failed for input 1534236469. The expected solution, in that case, is zero but our program print something else, see,  if you can spot the bug, and fix it.

If you like to solve programming problems like this, you will also enjoy solving the following coding problems from Java Interviews :
  • How to reverse words in String in Java? (solution)
  • How to swap two integers without using a temporary variable? (solution)
  • Top 50 Java Programs from Coding Interviews (see here)
  • 5 Free Data Structure and Algorithms Courses for Programmers (courses)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)
  • How to print the Fibonacci series in Java without using Recursion? [solution]
  • How to check if an integer is a power of two without using division or modulo operator?[hint]
  • How to check if a String is a Palindrome in Java? [solution]
  • 21 String Coding Problems from interviews (string problems)
  • How to find the missing number in a sorted array in Java? [answer]
  • How to find all permutations of String in Java? [solution]
  • Top 20 String coding interview questions (see here)
  • 50+ Data Structure and Algorithms Problems from Interviews (questions)
  • Grokking Algorithms for Programmers (Book review)
  • How to remove an element from the array without using a third-party library (check here)
  • How to find the largest and smallest number in an array in Java (read here)
  • How to find two maximum numbers on an integer array in Java (check here)
  • 7 Best courses to learn data structure and algorithms (best courses)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data Structure courses on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course. 

Lastly, what is your favorite Java coding exercise? Palindrom, Prime Number, Producer consumer problem , or this one?  Do let me know in comments. 

4 comments:

  1. if input is 1534236469 then what is the result according to me it should be 0;

    ReplyDelete
  2. while(val>0){
    int last=val%10;
    int newResult=result*10+last;

    System.out.println(result);
    if ((newResult - last) / 10 != result)
    { return 0; }
    result=newResult;

    val=val/10;


    }

    ReplyDelete
    Replies
    1. why is this step needed?

      if ((newResult - last) / 10 != result)

      Delete
  3. Using java 8 there is a method for Math.multiplyExact which throws exception for integer overflow..this resolved the issue and all test cases passed
    try{
    reverse = Math.multiplyExact(reverse,10) + rem;
    } catch(ArithmeticException e)
    {
    return 0;
    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.