版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83862588
题目:
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.
解释:
题目要求我们是在32位的环境中解决问题??这如何知道是不是超出范围?辣鸡题目…
python代码:
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
y=0
if x<0:
x=str(x)[1:]
y=-int(x[::-1])
else:
y=int(str(x)[::-1])
if y<-2**31 or y>2**31-1:
y=0
return y
c++代码:
#include <algorithm>
#include <cstdlib>
#include <string>
using namespace std;
class Solution {
public:
int reverse(int x) {
long result=0;
bool flag=false;
if (x<0)
flag=true;
x=abs(x);
string s=to_string(x);
std::reverse(s.begin(),s.end());
result=atol(s.c_str());
if (result<INT_MIN ||result>INT_MAX)
return 0;
return flag?-result:result;
}
};
总结: