mycode
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ a = str(x) if a[0] == '-': flag = '-' a = a[1:] else : flag = '' a = a[::-1] while True: if a[0] == '0': if len(a) > 1: a = a[1:] else: return 0 else: a = int(flag+a) if a > 2147483647 : return 0 elif a < -2147483648 : return 0 else: return a
注意:用int(x)时,会自动把x前面的0去掉
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ a = str(x) if a[0] == '-': flag = '-' a = a[1:] else : flag = '' a = a[::-1] #while True: # if a[0] == '0': # if len(a) > 1: a = a[1:] # else: return 0 # else: a = int(flag+a) if a > 2147483647 : return 0 elif a < -2147483648 : return 0 else: return a
参考
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1]) return x if x < 2147483648 and x >= -2147483648 else 0