题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
链接:https://oj.leetcode.com/problems/reverse-integer/
解法:直接处理,注意溢出,leetcode加强了判题现在要处理溢出,以前的代码已经ac不了了。
solution by python:
class Solution:
# @return an integer
def isOk(self, x, n, sym):
max_int = 214748364
if x > max_int: return False
if x == max_int:
if sym==-1 and n>8: return False
if sym==1 and n>7: return False
return True
def reverse(self, x):
symbol = -1 if x<0 else 1
x = abs(x)
ans = 0
while x > 0:
n = x %10
if self.isOk(ans,n,symbol):
ans = ans*10 + n
x /= 10
else: return 0
return symbol*ans