您的位置:首页 > 其它

LeetCode7 Reverse Integer 题解(数的逆序)

2018-03-19 14:49 337 查看

LeetCode7 Reverse Integer 题解

题目

Given a 32-bit signed integer, reverse digits of an integer.

输入输出实例

input:123

output:321

intput:120

output:21

input:-123

output:-321

核心算法

int result = 0;
while(n!=0){
result = result*10+n%10;
n /= 10;
}


其他注意的地方

考虑特殊情况,有时需要特判

如 input:0

input:-2147483648(即INT_MIN)

数据溢出:

如:long long a = 1<<31-1;

等号右边溢出 1默认为int型,1<<31溢出

修改:long long a = 1ll<<31-1

或者 long long a = INT_MAX;

代码

class Solution {
public:
int reverse(int x) {
string s;
if(x>=0){
long long result = 0;
while(x!=0){
result = result*10+x%10;
x/=10;
}

if(result<=INT_MAX)
return result;
else
return 0;
}else{
long long a = x;
a = -1ll*a; //注意,若直接使用x=-1*x的话,当遇到输入x为INT_MIN时,会出现数据溢出
long long result = 0;
while(a!=0){
result = result*10+a%10;
a/=10;
}
if(result<=1ll<<31)  //注意:若使用1<<31,会出现数据溢出(1默认为int型) int的数据范围为[-1<<31 - 1<<31-1]
return (-1*result);
else
return 0;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息