[LeetCode] 9. 回文数

题目链接:https://leetcode-cn.com/problems/palindrome-number/

题目描述:

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例:

示例 1:

输入: 121
输出: true

示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

思路:

当然直接用字符串反转比较就行了

也可以通过数学运算,找到取反的数

代码:

python

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if (x < 0) or (x != 0 and x % 10 == 0):
            return False
        cmp_num = 0
        while x > cmp_num:
            cmp_num = cmp_num * 10 + x % 10
            x //= 10
        #print(x,cmp_num)
        return x == cmp_num or x == cmp_num // 10

c++

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x != 0 && x % 10 == 0))
            return false;
        int cmp_num = 0;
        while(x > cmp_num){
            cmp_num = cmp_num * 10 + x % 10;
            x /= 10;
        }
        return x == cmp_num || x  == cmp_num/10;
        
    }
};

猜你喜欢

转载自www.cnblogs.com/powercai/p/10736911.html