Press "Enter" to skip to content

9. 回文数

方法一:

反转一半数字:例如输入1331,我们可以将数字“1331”的后半部分从“31”反转成“13”在和前半部分进行比较,如果二者相同我们就得知数字“1331”是回文数

C 代码解法

#include<stdbool.h>

bool isPalindrome(int x){
    // 特殊情况处理:如果 x 是负数或者末尾是 0 的非零数,则不可能是回文数
    if (x < 0 || (x != 0 && x % 10 == 0)){
        return false;
    }

    long reversed_num = 0;
    int original_x = x;

    //反转 x 的一半
    while (x > 0){
        int digit = x % 10;
        reversed_num = reversed_num * 10 + digit;
        x /= 10;
    }

    // 如果原始数字长度是奇数,去掉最后一位
    if (original_x == reversed_num || original_x == reversed_num / 10){
        return true;
    } else {
        return false;
    }
}

Python3 代码解法

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x = str(x)
        if x == x[::-1]:
            return True
        else:
            return False

Source: LeetCode(The title reproduced in this blog is for personal study use only)

Be First to Comment

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注