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
}
相关推荐
玖玥拾8 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
Awna9 小时前
Golang 大小写可见性规范
开发语言·后端·golang
Hi李耶9 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
进击的程序猿~13 小时前
Go 内存分配与垃圾回收源码深度学习手册
开发语言·后端·golang
geovindu13 小时前
go:Bit Operation Algorithm
开发语言·后端·算法·golang·位运算法
白白白小纯14 小时前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
zander25815 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
yyds_yyd_1008616 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
lueluelue471 天前
LeetCode:链表
算法·leetcode·链表