leetcode Question 84: Reverse Integer

Reverse Integer


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

Analysis:

Simple question. Just be careful with the last digit and positive/negative.
Also be careful with the corner cases.
Idea is to keep x/10 for the original int and *10 for the result int + x%10.


Note that in Python, when compute -1/10 the result is -1 not the expected 0. 
This is because the "floor" function for the int division. 
E.g.,  math.floor(0.89) = 0
          math.floor(-0.89) = -1


So I check the positive and negative sign in the python code.
The number 214748364 in python code is the maxint/10 = 2147483647/10.



Code(C++):


class Solution {
public:
    int reverse(int x) {
        int  res = 0;
        while (x!=0){
            if (res > INT_MAX/10 || res < INT_MIN/10){
                return 0;
            }
            res = res*10+ x%10;
            x= x/10;
        }
        return res;
    }
};

Code (Python):

class Solution:
    # @return an integer
    def reverse(self, x):
        res = 0
        if x>=0:
            pos = True
        else:
            pos  = False
            x = -x
        while not x == 0:
            if res > 214748364:
                return 0
            else:
                res = res*10 + x%10
                x = x/10
        if pos:
            return res
        else:
            return -res
        

8 comments:

  1. Replies
    1. Sorry, I don't really get what you mean by overflow cases, could you give an example?

      Delete
    2. Assuming an integer is 32-bits, if x = 2147483643, the reversed integer would be 3463847712, which certainly overflows. I think you need to handle this in your code, cause otherwise the problem is just too trivial and meaningless. Also, it is not necessary to check whether x is positive or not, just replace the termination condition of while loop with x!=0 and your code will handle all positive and negative cases correctly.

      Delete
    3. just take a bigger type for res such as long , and put an extra condition saying if res > INT_MAX return 0

      Delete
    4. can anyone explain why this weird test case:
      Input: 1534236469
      Output: 1056389759
      Expected: 0

      Delete
    5. @Yu Zhu are you sure your either of above solution got accepted at leetcode ?
      because I got WA :

      Input: 1534236469
      Output: 1056389759
      Expected: 0

      you didn't take care of overflow cases. Did you?

      Delete
    6. Thanks for your reply, I think it might because this post was written long time ago and leetcode oj has changed some of the test cases. Now I have changed the code and tested on OJ.

      Thanks.


      Delete
  2. Thanks great help ..!!!!!!!!!!!!!

    ReplyDelete