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
}
相关推荐
样例过了就是过了1 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz1 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧1 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode
小肝一下3 小时前
每日两道力扣,day2
c++·算法·leetcode·职场和发展
米粒14 小时前
力扣算法刷题 Day 31 (贪心总结)
算法·leetcode·职场和发展
AlenTech4 小时前
647. 回文子串 - 力扣(LeetCode)
算法·leetcode·职场和发展
py有趣4 小时前
力扣热门100题之合并两个有序链表
算法·leetcode·链表
8Qi85 小时前
LeetCode热题100--45.跳跃游戏 II
java·算法·leetcode·贪心算法·编程
lucky九年5 小时前
GO语言模拟C++封装,继承,多态
开发语言·c++·golang
北顾笙9805 小时前
day12-数据结构力扣
数据结构·算法·leetcode