翻转整数,注意几个坑点…
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
注意点:负数和越界吧…
给出多个方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ flag = 1 if x < 0 : flag = -1 x *= -1 rt = 0 while x : rt = rt * 10 + x % 10 x /= 10 if rt >= math.pow(2, 31) : return 0 return rt * flag |
字符串方法:
1 2 3 4 5 6 7 8 9 10 |
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ rt = int(str(abs(x))[::-1]) if rt > math.pow(2, 31) : return 0 return rt * cmp(x, 0) |
比上面的方法慢,但是短码看起来舒服。不过我不知道能不能更快了…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Solution { public: int reverse(int x) { long rt = 0; bool flag = true; if(x < 0) { x = -x; flag = false; } while(x) { rt=rt*10 + x%10; x/=10; } if(rt < 0 || rt > INT_MAX) return 0; if(!flag) return -rt; return rt; } }; |
心疼,提交的越来越慢…