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
}
相关推荐
程序员-King.25 分钟前
day126—二分查找—寻找旋转排序数组中的最小值(LeetCode-153)
算法·leetcode·二分查找
菜鸟233号25 分钟前
力扣494 目标和 java实现
java·数据结构·算法·leetcode
有一个好名字25 分钟前
力扣-字符串解码
java·算法·leetcode
nbsaas-boot26 分钟前
Go 语言中的集合体系:从语言设计到工程实践
开发语言·后端·golang
sin_hielo32 分钟前
leetcode 1266
数据结构·算法·leetcode
接着奏乐接着舞。33 分钟前
Go 一小时上手指南:从零到运行第一个程序
开发语言·后端·golang
代码N年归来仍是新手村成员12 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
踩坑记录13 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
清铎16 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
踩坑记录16 小时前
leetcode hot100 42 接雨水 hard 双指针
leetcode