您的位置:首页 > 其它

LeetCode (7)Reverse Integer

2017-04-18 23:07 381 查看

(7)Reverse Integer

题目:把数字倒过来。

例子:x = 123, return 321。

再例:x = -123, return -321。

另:输入是32位有符号整数,当超出范围的时候,输出0。

根据这个题目,想到的就是字符串,直接使用字符串处理就可以反过来输出。但是通过另外的最后一句话,我们不难发现,数字的范围仅在-2^31~2^31之间,那么需要处理的就只有0,数字超过10位或在等于十位的时候,与2^31比较大小就可以了。

下面是代码:

class Solution {
public:
int reverse(int x) {
string str = "";
int i = 0;
unsigned int x1 = x>0?x:(0-x);
if(x == 0){
return 0;
}
while(x1!=0){
str += ( x1 % 10 ) + '0';
i ++;
x1 = x1/10;
}
if(str.size()>10){
return 0;
}
if((str.size()==10)&&(str.compare("2147483647")>0)){
return 0;
}
else{
if(x<0){
return 0-std::stoi(str);
}
else{
return std::stoi(str);
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: