7. 整数反转
原创
©著作权归作者所有:来自51CTO博客作者喜欢打篮球的普通人的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.题目:https://leetcode-cn.com/problems/reverse-integer/
2.思路:
(1)2^ 31-1=2147483647,-2^31=-2147483648
(2)注意溢出问题,以及整数如何取出每一位,以及如何用很多位组合成整数
3.代码:
参考:https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/
https://leetcode-cn.com/problems/reverse-integer/solution/hua-jie-suan-fa-7-zheng-shu-fan-zhuan-by-guanpengc/
class Solution {
public:
int reverse(int x) {
int res=0;
int INTMAX=2147483647 ;
int INTMIN=-2147483648;
while (x!=0)
{
int pop=x%10;
x=x/10;
if (res>INTMAX/10 || (res==INTMAX/10 && pop>7))
return 0;
if (res<INTMIN/10 || (res==INTMIN/10 && pop<-8))
return 0;
res=res*10+pop;
}
return res;
}
};
下面的也可以通过
class Solution {
public:
int reverse(int x) {
long long res=0;
int INTMAX=2147483647 ;
int INTMIN=-2147483648;
while (x!=0)
{
int pop=x%10;
x=x/10;
if (res>INTMAX/10 )
return 0;
if (res<INTMIN/10 )
return 0;
res=res*10+pop;
}
return res;
}
};