思路
- 定义res准备返回
- 循环的将x从末尾到开头拼至res后面
- 每次拼接时检查当前res是否超过32位的有符号整数的范围 [−231, 231 − 1]
- 超过返回0
- 不超过继续拼接
- 循环结束;返回res
java
public int reverse(int x) {
int res = 0;
while (x != 0) {
if (res < Integer.MIN_VALUE / 10 || res > Integer.MAX_VALUE / 10) {
return 0;
}
int i = x % 10;
res = res * 10 + i;
x /= 10;
}
return res;
}
go
func reverse(x int) int {
res := 0
for x != 0 {
if res < math.MinInt32/10 || res > math.MaxInt32/10 {
return 0
}
i := x % 10
res = res*10 + i
x /= 10
}
return res
}