How to reverse Integer in Java - LeetCode Solution

LeetCode has a problem to reverse digits of an integer number without using any library method like reverse() method of StringBuffer. In LeetCode, you can solve this problem with many different languages e.g. Java, C, C++, C#, Python, Ruby and even JavaScript. BTW, in the article, we will learn how to solve this problem in Java. Before approaching 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 which is accepted by LeetCode, which has thousands of test cases to test your solution.


For example, you need to consider not just about positive integer but also about negative integer. Remember, a positive integer can also be written using + sign, so you need to handle that as well. If the integer's last digit is 0, what should the output be? i.e. 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.





Java Solution : Reverse Integer without library method

Here is my Java program to solve this problem of reversing integer number without using any direct library method. The crux of this problem is how to use division and modulo operator 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 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 last 2 digits by dividing your number by 10 twice.

Similarly, you can use 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. Now the question comes, how do you arrange those digits in reverse order? Well, you can use just opposite i.e. multiplication and addition to creating a new number with digits of the old number in reverse order.  I have used following logic to assemble digits into reverse order :

reverse = reverse * 10 + lastDigit;

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

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 last digit, second with 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 Programming Interviews Exposed and Cracking the Coding Interview, two of the most useful books 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 plus sign and 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 case 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.

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. 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 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)
  • How to print 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 Palindrome in Java? [solution]
  • How to find the missing number in a sorted array in Java? [answer]
  • How to find all permutation of String in Java? [solution]
  • How to remove element from array without using third party library (check here)
  • How to find largest and smallest number in an array in Java (read here)
  • How to find two maximum number on integer array in Java (check here)

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.


1 comment:

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

    ReplyDelete