首页 > 其他 > 详细

LeetCode-7. Reverse Integer | 整数反转

时间:2021-02-04 00:07:25      阅读:28      评论:0      收藏:0      [点我收藏+]

题目

LeetCode
LeetCode-cn

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!