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
}
相关推荐
cpp_25012 分钟前
P10109 [GESP202312 六级] 工作沟通
数据结构·c++·算法·题解·洛谷·gesp六级
ʚ希希ɞ ྀ5 分钟前
全排列 --- 回溯
算法·leetcode·深度优先
8Qi812 分钟前
LeetCode 124. 二叉树中的最大路径和(Hard)
算法·leetcode·二叉树·递归
And_Ii16 分钟前
LeetCode 1. 两数之和 python
数据结构·算法·leetcode
cpp_250126 分钟前
P10377 [GESP202403 六级] 好斗的牛
数据结构·c++·算法·题解·洛谷·gesp六级
Navigator_Z8 小时前
LeetCode //C - 1089. Duplicate Zeros
c语言·算法·leetcode
语戚11 小时前
力扣 3161. 块放置查询:线段树解法(Java 实现)
java·算法·leetcode·面试·线段树·力扣·
8Qi813 小时前
LeetCode 23. 合并 K 个升序链表 —— 小顶堆(PriorityQueue)
数据结构·算法·leetcode·链表·
Lsk_Smion15 小时前
力扣实训 _ [200].岛屿数量
算法·leetcode·深度优先
Lsk_Smion17 小时前
力扣实训 _ [543].二叉树的直径 _ [23].合并K个升序列表
数据结构·算法·leetcode