class Solution { public int reverse(int x) { int rev = 0; while (x != 0) { int pop = x % 10; x /= 10; if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0; if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; } }
Python
python没有溢出问题,处理这题投机取巧
1 2 3 4 5 6 7 8 9 10 11 12 13
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x < 0: result = -int(str(-x)[::-1]) # 字符串倒序输出 else: result = int(str(x)[::-1]) if result < -2147483648 or result > 2147483647: return 0 return result