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 @   Zoctopus_Zhang  阅读(55)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2017-02-03 Python中的高级turtle(海龟)作图(续)
2017-02-03 Python中的高级turtle(海龟)作图
2017-02-03 使用Python的turtle(海龟)模块画图
// 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);
点击右上角即可分享
微信分享提示