Given a 32-bit signed integer, reverse digits of an integer. (翻转一个有符号整形数值字符串)
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: ([−2^{31}, 2^{31} − 1]). For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class : defreverse(self, x): """ :type x: int :rtype: int """ string = str(x) n = len(string) if string[0] == '-': result = [string[n-i] for i in range(1, n)] result = ['-'] + result else: result = [string[n-i-1] for i in range(n)] re = int("".join(result)) if re > pow(2, 31) - 1or re < - pow(2, 31): re = 0 return re
class : defreverse(self, x): """ :type x: int :rtype: int """ abso_x = abs(x) result = 0 while abso_x != 0 : a = abso_x % 10 abso_x = abso_x // 10 result = result * 10 + a if x < 0: result *= -1 if result > (pow(2, 31) - 1) or result < -pow(2, 31): return0 return result
近期评论