[Leetcode]Reverse Integer
2015-02-04 14:21
411 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
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
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
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
相关文章推荐
- leetcode-- Reverse Integer
- leetcode-7-Reverse Integer
- leetcode 007 —— Reverse Integer
- LeetCode:07: Reverse Integer
- LeetCode - Refresh - Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode (2). Reverse Integer
- LeetCode 7 Reverse Integer
- leetcode-Reverse Integer
- 【leetcode】Reverse Integer
- LeetCode: Reverse Integer
- leetCode:Reverse Integer
- LeetCode - Reverse Integer
- [LeetCode84]Reverse Integer
- Leetcode-Reverse Integer
- leetcode-7. Reverse Integer
- LeetCode - 7 - Reverse Integer
- leetcode第7题,Reverse Integer
- LeetCode 之 Reverse Integer
- LeetCode 7: Reverse Integer