题目(来自leetcode网站):
题目的意思是把 输入的整数倒叙输出,不改变符号,且需要对整数的范围进行判断;
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解答:
#PYTHON版本
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x <-2**31 or x >(2**31) -1:
return 0
else:
b = -int(str(x)[::-1][:-1]) if x <0 else int(str(x)[::-1])
if b <-2**31 or b >(2**31) -1:
return 0
else:
return b
#C++版本
#inlude<cstring>
#include <sstream>
class Solution {
public:
int reverse(int x) {
int result=0;
if(x < pow(-2,31) || x >pow(2,31)-1){
return 0;
}
else{
string s=to_string(x);
x>=0? s=s.substr(0,s.size()) : s=s.substr(1,s.size()-1);
s=reverse_str(s);
stringstream ss;
ss<<s;
ss>>result;
x>=0? result:result=0-result;
if(result ==pow(2,31)-1 ||result==pow(-2,31)+1){
return 0;
}else{
return result;
}
}
}
string reverse_str(string s){
string b;
for(int i=0;i<s.size();i++){
b+=s[s.size()-1-i];
}
return b;
}
};