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
}
相关推荐
All for pursuit.7 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
谢亮_vipxieliang9 小时前
Go map与结构体的正确使用
开发语言·golang·哈希算法
microrain9 小时前
先应答,再入库:SagooIoT 接入 GB/T 32960 的四层宿主改造
物联网·golang·开源·sagooiot
夏幻灵14 小时前
每日一题:LeetCode 3:无重复字符的最长子串——滑动窗口思路详解
算法·leetcode·职场和发展
无忧.芙桃14 小时前
C++ 并查集详解:原理、实现与应用
c语言·c++·算法·leetcode
蛋蛋的就会顺顺的14 小时前
hot100——二叉树
java·数据结构·算法·leetcode·力扣
Nil20817 小时前
leetcode 55跳跃游戏
算法·leetcode·游戏
longlongzihan17 小时前
LeetCode 128. 最长连续序列 —— 从排序到哈希集合
数据结构·c++·算法·leetcode·排序算法·哈希表
谢亮_vipxieliang18 小时前
Go defer、panic与recover核心知识点
开发语言·后端·golang
谢亮_vipxieliang19 小时前
Go基础数据类型全解
开发语言·后端·golang