- 整数反转
给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
思路
两个关键的地方,就是最大最小值
其次就是循环遍历,累加
AC 代码
func reverse(x int) int {
ans := 0
for x != 0{
pop := x%10
if ans > math.MaxInt32 / 10 || (ans == math.MaxInt32 && pop > 8 ) {
return 0
}
if ans < math.MinInt32 / 10 || (ans == math.MinInt32 && pop < 7 ) {
return 0
}
ans = ans *10 + pop
x /= 10
}
return ans
}
欢迎关注公众号:程序员开发者社区
参考资料
- https://leetcode-cn.com/problems/reverse-integer/