Golang | Leetcode Golang题解之第9题回文数

题目:

题解:

Go 复制代码
func isPalindrome(x int) bool {
    // 特殊情况:
    // 如上所述,当 x < 0 时,x 不是回文数。
    // 同样地,如果数字的最后一位是 0,为了使该数字为回文,
    // 则其第一位数字也应该是 0
    // 只有 0 满足这一属性
    if x < 0 || (x % 10 == 0 && x != 0) {
        return false
    }

    revertedNumber := 0
    for x > revertedNumber {
        revertedNumber = revertedNumber * 10 + x % 10
        x /= 10
    }

    // 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
    // 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
    // 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
    return x == revertedNumber || x == revertedNumber / 10
}
相关推荐
YLCHUP42 分钟前
【模拟&STL】题解:AT_abc203_e [ABC203E] White Pawn_基础算法_数据结构_STL模板库_AtcoderABC_C++算法竞赛
数据结构·c++·算法·leetcode·动态规划·哈希算法·近邻算法
紧跟先前的步伐44 分钟前
Go AI Agent 实战 19|工具定义、参数 Schema 与工具注册表
人工智能·ai·golang·1024程序员节
(●—●)橘子……1 小时前
力扣 第525场周赛 练习理解
数据结构·python·学习·算法·leetcode
FungLeo1 小时前
成为全栈·Go 后端篇·重写之前先锁基线:契约、Node 版本与行为清单
golang·node.js·go·openapi·契约测试·成为全栈
wenyq71 小时前
LeetCode 152. Maximum Product Subarray
java·算法·leetcode
念何架构之路2 小时前
OpenTelemetry核心概念
后端·目标跟踪·golang·c#·linq
紧跟先前的步伐2 小时前
Go AI Agent 实战 20|接入 DeepSeek 原生 Tool Calling
人工智能·ai·golang·1024程序员节
文丑颜不良啊2 小时前
LeetCode1181~1200题目解析
java·leetcode