Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
反转数字~有很多细节都要注意,例如负数问题,还有整数越界问题~虽然python不用处理整数溢出的问题,但在这题里如果不处理的话不能AC,所以在结尾判断了一下res是否大于2的31次方,如果大于的话就返回0
class Solution:
# @return an integer
def reverse(self, x):
res, num, sign = 0, abs(x), -1 if x < 0 else 1
while num:
num, res = num // 10, res * 10+ num % 10
return 0 if res > pow(2, 31) else res * sign