问:给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
例:
输入:x = 123
输出:321
原题链接:https://leetcode.cn/problems/reverse-integer/
答:
class Solution {
public int reverse(int x) {
int n;
int t = 0;
if(x == 0)
return 0;
//2的31次方等于2147483648
while(x != 0)
{
n = x % 10;
//考虑溢出的问题
if(t > 214748364 || (t == 214748364 && n > 7))
return 0;
if(t < -214748364 || (t == -214748364 && n < -8) )
return 0;
t = t * 10 + n;
x = x / 10;
}
return t;
}
}