Simple problem, but still need to care about some cases.
One solution is to use Python's powerful string process ability, and another is to process the number.
Solution 1:
# T:O(lgn) S :O(1) class Solution: # @param {integer} x # @return {integer} def reverse(self, x): sign = 1 if x < 0: sign = -1 x = sign * int(str(abs(x))[::-1]) if x > 2147483647 or x < -2147483648: return 0 else: return xRun Time: 76 ms
Solution 2:
# T:O(lgn) S :O(1) class Solution: # @param {integer} x # @return {integer} def reverse(self, x): if not x: # if x = 0 return 0 tmp = abs(x) # get positive value result = 0 while tmp >= 10: result = result * 10 + tmp % 10 tmp //= 10 else: result = result * 10 + tmp if x < 0: result = -result if result < -2147483648 or result > 2147483647: return 0 return resultRun Time: 84 ms
No comments:
Post a Comment