整数反转
Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
1 | Input: 123 |
Example 2:
1 | Input: -123 |
Example 3:
1 | Input: 120 |
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: . For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题目大意
对于提供的32位有符号整型数字按位反转得到另一组整型。需要注意的两点:
有符号,即会有负数
按位反转后,可能会超出32位整型的范围,导致溢出,这里需要做处理
32位整型取值范围:-2147483648 ~ 2147483647
解题思路
Tag:数学
- 通过循环将数字 x 按位拆分,在计算新值时判断是否溢出
- 溢出条件有两个:
- 一个是大于整数最大值
math.MaxInt32
- 一个是小于整数最小值
math.MinInt32
- 一个是大于整数最大值
- 定义计算结果为
rev
,下一位为pop
- 从
rev * 10 + pop > math.MaxInt32
这个条件来看- 当出现
rev > math.MaxInt32 / 10
且 还有pop
需要添加时,则一定溢出 - 当出现
ans == math.MaxInt32 / 10
且pop > 7
时,则一定溢出,7
是2^31 - 1
的个位数
- 当出现
- 从
rev * 10 + pop < math.MinInt32
这个条件来看- 当出现
rev < math.MinInt32 / 10
且 还有pop
需要添加时,则一定溢出 - 当出现
rev == math.MinInt32 / 10
且pop < -8
时,则一定溢出,8
是-2^31
的个位数
- 当出现
- 从
代码
1 | func reverse(x int) int { |