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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题目大意:反转数字,ruoc若超过int的表示范围,则返回0;
解题思路:原始数据不会超过11位,也就是说不管怎么反转,一定不会超过long long int的表示范围,用long long int进行存储,反转,然后再判断是否在int表示范围内
C++
class Solution {
public:
int reverse(int x) {
string s = to_string(x);
if(x < 0)
std::reverse(s.begin()+1, s.end());
else
std::reverse(s.begin(), s.end());
long long int result = stoll(s);
return (result < INT_MIN || result > INT_MAX) ? 0 : result;
}
};
Python
class Solution(object):
def reverse(self, x):
flag = -1 if x < 0 else 1
res = flag * int(str(abs(x))[::-1])
return res if (-2**31) <= res <= (2**31-1) else 0