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
}
相关推荐
bybitq1 分钟前
Leetcode-3780-Python
python·算法·leetcode
如何原谅奋力过但无声2 分钟前
【力扣-Python-75】颜色分类(middle)
python·算法·leetcode
玖剹3 分钟前
哈希表相关题目
数据结构·c++·算法·leetcode·哈希算法·散列表
练习时长一年1 小时前
LeetCode热题100(最小栈)
java·算法·leetcode
Tisfy2 小时前
LeetCode 955.删列造序 II:模拟(O(mn)) + 提前退出
算法·leetcode·字符串·题解·遍历
Tony Bai2 小时前
Goroutine “气泡”宇宙——Go 并发模型的新维度
开发语言·后端·golang
im_AMBER2 小时前
Leetcode 82 每个字符最多出现两次的最长子字符串 | 删掉一个元素以后全为 1 的最长子数组
c++·笔记·学习·算法·leetcode
java修仙传2 小时前
力扣hot100:旋转排序数组中找目标值
算法·leetcode·职场和发展
YGGP3 小时前
【Golang】LeetCode 287. 寻找重复数
开发语言·leetcode·golang
前端小白在前进3 小时前
力扣刷题:千位分割数
javascript·算法·leetcode