7. Reverse Integer(翻转整数)
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution { public: int reverse(int x) { int res = 0; while(x!=0) { if (res < INT_MIN/10 || res > INT_MAX/10) return 0; int cur = x%10; x = x/10; res = res*10 + cur; } return res; } };
用的是Python 转换成str ,然后翻转,需要注意
1.翻转之后如果溢出,输出0
1 class Solution: 2 3 def reverse(self, x): 4 """ 5 :type x: int 6 :rtype: int 7 """ 8 neg = x<0 9 res = int(''.join(str(abs(x))[::-1])) 10 if res > 2**31: 11 res = 0 12 if neg: 13 res = -res 14 return res