(LeetCode)Reverse Integer --- 反转整数
2016-10-14 10:01
666 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
Subscribe to see which companies asked this question
解题分析:
注意读入和返回的数都是 int 型的,这时就要考虑反转后这个数会不会超 int,
超的话就返回 0 。这时处理数时最好用比 int 大的类型,不然恐怕会超范围。
当然也可以用 int :
还有一点就是还要考虑前导零。
这里在python中有相应的函数来处理,比较方便。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
def reverse(self, x):
revx = int(str(abs(x))[::-1])
if revx > math.pow(2, 31):
return 0
else:
return revx * cmp(x, 0)
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
Subscribe to see which companies asked this question
解题分析:
注意读入和返回的数都是 int 型的,这时就要考虑反转后这个数会不会超 int,
超的话就返回 0 。这时处理数时最好用比 int 大的类型,不然恐怕会超范围。
当然也可以用 int :
if (result > (INT_MAX/10))
还有一点就是还要考虑前导零。
这里在python中有相应的函数来处理,比较方便。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
def reverse(self, x):
revx = int(str(abs(x))[::-1])
if revx > math.pow(2, 31):
return 0
else:
return revx * cmp(x, 0)
相关文章推荐
- leetcode——Reverse Integer 反转整数数字(AC)
- Leetcode:Reverse Integer ,整数反转
- LeetCode--Reverse Integer(整数反转)Python
- 【LeetCode】- Reverse Integer(将一个整数反转)
- 【leetcode】Reverse Integer整数反转----Java代码实现
- LeetCode7——Reverse Integer(将一个整数反转,注意溢出的处理)
- LeetCode Reverse Integer 反转整数
- [LeetCode-7] Reverse Integer(反转整数)
- [leetcode] Reverse Integer 反转一个整数
- leetcode reverse Integer(反转整数)
- [leetcode 7] Reverse Integer(整数反转) c函数实现
- [Leetcode] reverse integer 反转整数
- Leetcode Reverse Integer 反转整数
- LeetCode 7 :Reverse Integer ---- 反转int整数
- [置顶] [LeetCode] Reverse Integer 整数反转
- [Leetcode #7]Reverse Integer整数反转、逆向打印整数
- LeetCode 7. Reverse Integer 整数反转
- LeetCode 7 Reverse Integer(反转数字)
- ReverseInteger 给出一个整数,反转这个整数
- [Leetcode #7]Reverse Integer整数反转、逆向打印整数