Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-231 <= x <= 231 - 1
通过题目可以看出来,这道题是让我们翻转一个整数,比如123,个位是1十位是2百位是3,反转后个位是3十位是2百位是1。
照着官方题解的解法一:弹出和推入数字 & 溢出前进行检查写的Go版本
func reverse(x int) int {
rev := 0
INT_MIN:=-2147483648
INT_MAX:=2147483647
for x != 0 {
pop := x % 10
x /= 10
if rev > INT_MAX / 10 || rev == INT_MAX / 10 && pop >7 {
return 0
}
if rev < INT_MIN / 10 || rev == INT_MIN / 10 && pop < -8 {
return 0
}
rev = rev * 10 + pop
}
return rev
}
leetcode-cn执行:
执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:2.1 MB, 在所有 Go 提交中击败了95.50%的用户
leetcode执行:
Runtime: 4 ms, faster than 41.60% of Go online submissions for Reverse Integer.
Memory Usage: 2.3 MB, less than 14.22% of Go online submissions for Reverse Integer.
LeetCode-7. Reverse Integer | 整数反转
原文:https://www.cnblogs.com/OctoptusLian/p/14370256.html