题目描述
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
练习地址
实现
- 目前在一般的电脑中,int占用4字节,32比特,数据范围为
- − 2147483648 — 2147483647 [ − 2 31 — 2 31 − 1 ] -2147483648—2147483647 [-2^{31} —2^{31}-1] −2147483648—2147483647[−231—231−1]
- Integer.MAX_VALUE 、Integer.MIN_VALUE
- 实现
解法
class Solution {
public int reverse(int x) {
int res = 0;
while (x != 0) {
int carry = x % 10;
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && carry > 7)) {
return 0;
}
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && carry < -8)) {
return 0;
}
res = res * 10 + carry;
x /= 10;
}
return res;
}
}