7. Reverse Integer(python+cpp)(int範圍的問題)
阿新 • • 發佈:2018-11-09
題目:
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;
}
};
總結: