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(object): defreverse(self, x): """ :type x: int :rtype: int """ if x < 0: isNegative = True elif x > 0: isNegative = False else: return x x = str(abs(x))[::-1] first = True result = '' for char in x: if char == '0'and first: continue else: first = False result = result + char x = int(result) if isNegative: if -x < -2147483648: return0 else: return -x else: if x > 2147483647: return0 else: return x
想法:转换为字符串进行反转
Best Solution
Python
1 2 3 4
defreverse(self, x): s = cmp(x, 0) r = int(`s*x`[::-1]) return s*r * (r < 2**31)
想法:
**意为乘方
cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
近期评论