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
}
相关推荐
evans在进步1 天前
LeetCode 64:最小路径和——Java 原地动态规划详解
java·leetcode·动态规划
Tisfy1 天前
LeetCode 1386.安排电影院座位:哈希表+位运算
算法·leetcode·散列表·题解·哈希表
Nil2081 天前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
敢敢のwings1 天前
智元 GO-2 与 AgiBot-World 深度解读
开发语言·后端·golang
FfHUCisI1 天前
Golang 数据库连接池深度调优
android·数据库·golang
程序员小八7771 天前
Java 快速转 Go
java·python·golang
土司大王1 天前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
zander2581 天前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲1 天前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
名字还没想好☜1 天前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go