卖萌的弱渣

I am stupid, I am hungry.

Reverse Integer

Reverse digits of an integer.

  • Example1: x = 123, return 321
  • Example2: x = -123, return -321

Note

  • Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

  • If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

  • Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

  • For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution

(Reverse-Integer.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        isNeg = False
        if x < 0:
            isNeg = True
            x = -x
        ret = 0

        if x == 0:
            return ret

        while x != 0:
            ret = 10 * ret + (x%10)
            x = x/10

        if isNeg == True:
            ret = -ret
        if ret < -(1<<31) or ret > (1<<31)-1:
            return 0
        return ret