LeetCode – Reverse Integer

LeetCode - Reverse Integer:

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

1. Naive Method

We can convert the integer to a string/char array, reverse the order, and convert the string/char array back to an integer. However, this will require extra space for the string. It doesn't seem to be the right way, if you come with such a solution.

2. Efficient Approach

Actually, this can be done by using the following code.

public int reverse(int x) {
	//flag marks if x is negative
	boolean flag = false;
	if (x < 0) {
		x = 0 - x;
		flag = true;
	}
 
	int res = 0;
	int p = x;
 
	while (p > 0) {
		int mod = p % 10;
		p = p / 10;
		res = res * 10 + mod;
	}
 
	if (flag) {
		res = 0 - res;
	}
 
	return res;
}

3. Succinct Solution

This solution is from Sherry, it is succinct and it is pretty.

public int reverse(int x) {
    int rev = 0;
    while(x != 0){
        rev = rev*10 + x%10;
        x = x/10;
    }
 
    return rev;
}

Handle Out of Range Problem

As we form a new integer, it is possible that the number is out of range. We can use the following code to assign the newly formed integer. When it is out of range, throw an exception.

try{
  result = ...;
}catch(InputMismatchException exception){
  System.out.println("This is not an integer");
}

Please leave your comment if there is any better solutions.

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. CodeCode54 on 2014-4-3

    This will not handle the cases where the the reversed integer will cause overflow. This case should be handled.

  2. ethan1786 on 2014-6-20

    overflow? which case do you mean?

  3. Michael Hildebrand-Faust on 2014-7-8

    The solution is incorrect. In each loop, p needs to become the input with the last digit hacked off, so p should be adjusted by p = ( p – mod) / 10; That is, not *just* dividing by 10 — you have to subtract the remainder (mod) form dividing by ten, *then* divide by 10. Otherwise, just continuing to divide by 10 will never get you to 0 (think about it), and you’re in an infinite loop, hence the overflow. Here’s an example of the correct solution written in javascript: http://jsfiddle.net/mhfaust/XSNyr/

  4. tony on 2014-7-13

    In Java, I think you can get 0 if an integer is continuing divided by 10.

  5. Sherry on 2014-7-23

    I don’t think it is necessary to check whether the parameter is positive or negative. For instance, -11/10 = -1; -11%10 = -1. So this program could be even shorter:

    public int reverse(int x) {

    int rev = 0;

    while(x != 0){

    rev = rev*10 + x%10;

    x = x/10;
    }

    return rev;
    }

    but basically they are the same.

  6. Stephen Boesch on 2014-8-14

    Nice code! And yes it supports negative numbers just fine.

  7. Nelson on 2014-9-11

    This code does not support the leading zero case too……

  8. Yuvraj on 2014-9-16

    For example, 1000000009 becomes 9000000001, which is more than the range of Integer in Java.

  9. Mika on 2014-11-8

    Leading zero case would not exist in this solution since the input type is int.

  10. jason on 2014-11-27

    Here is my code, which can handle the overflow case.

    int max = 1<<31;
    int ret = 0;

    for (; x != 0; x/=10) {
    if (ret != 0 && max/ret -10)
    return 0;

    ret = ret*10 + x%10;
    }

    return ret;

  11. nitin on 2015-1-8

    Really nice code..can u please explain what u have done..

  12. ryanlr on 2015-2-23

    Nice code!

  13. Taoufik Bdiri on 2015-4-11

    This is not an accepted solution in CodeLeet. You should handle the buffer overflow case and return 0 when it happens. Please update the solution as follows :

    public class Solution {
    public int reverse(int x) {
    int rev = 0;
    while (x != 0) {
    //Handel the buffer overflow : should be handeled before rev update
    if (rev != 0 && Integer.MAX_VALUE / rev -10)
    return 0;
    rev = rev * 10 + x % 10;
    x = x / 10;
    }
    return rev ;
    }
    }

  14. Taoufik Bdiri on 2015-4-11

    BufferOverflow already handeled by jason in a comment below.

  15. Yiyuan Zhang on 2015-4-12

    But we can not use this method in python. Because in python -1 / 10 = -1 🙁

  16. Noah on 2015-5-25

    Thanks. would you explain in more detail? Thanks

  17. Apurva Kumar Sinha on 2015-6-17

    This java code handles the overflow condition:

    public int reverse(int x) {

    long reverse = 0;

    while( x != 0 ){

    reverse = reverse * 10 + x % 10;

    x = x/10;

    }

    if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE)

    return 0;

    else

    return (int) reverse;

    }

  18. qeatzy on 2015-7-28

    if (ret != 0 && max/ret -10)
    when ret==-1, could receive signal SIGFPE.
    for example when x=-901000

  19. Ashish Ranjan on 2015-10-22

    i think there should be “or” between (max/ret-10)

  20. Ashish Ranjan on 2015-10-22

    no,sorry underdtood 😀

  21. Ankit Shah on 2016-2-11

    public int reverse(int x) {
    int n = Math.abs(x);
    long result = 0;
    while (n != 0) {
    result = (result * 10) + (n % 10);
    n = n / 10;
    }

    if (result > Integer.MAX_VALUE || result = 0 ? (int) result : (int) result * -1;
    }

  22. Brandon Donnelson on 2016-12-3

    This solution enhances to the succinct solution which doesn’t account for math greater than the integer data types max value.


    public int reverse(int x) {
    long rev = 0;

    while (x != 0) {
    rev = rev * 10 + x % 10;

    if ((x > 0 && rev > Integer.MAX_VALUE )|| (x < 0 && rev < Integer.MIN_VALUE)) {
    return 0;
    }

    x /= 10;

    }
    return (int) rev;
    }

Leave a comment

*