Fork me on GitHub
打赏

LeetCode-7. Reverse Integer | 整数反转

题目

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.

注意

  • 目前计划先把第一解法写出来,后期再添加优化的解法。
posted @ 2021-02-03 23:04  Zoctopus_Zhang  阅读(53)  评论(0编辑  收藏  举报
// function btn_donateClick() { var DivPopup = document.getElementById('Div_popup'); var DivMasklayer = document.getElementById('div_masklayer'); DivMasklayer.style.display = 'block'; DivPopup.style.display = 'block'; var h = Div_popup.clientHeight; with (Div_popup.style) { marginTop = -h / 2 + 'px'; } } function MasklayerClick() { var masklayer = document.getElementById('div_masklayer'); var divImg = document.getElementById("Div_popup"); masklayer.style.display = "none"; divImg.style.display = "none"; } setTimeout( function () { document.getElementById('div_masklayer').onclick = MasklayerClick; document.getElementById('btn_donate').onclick = btn_donateClick; var a_gzw = document.getElementById("guanzhuwo"); a_gzw.href = "javascript:void(0);"; $("#guanzhuwo").attr("onclick","follow('33513f9f-ba13-e011-ac81-842b2b196315');"); }, 900);