LeetCode简单题:9. 回文数(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/palindrome-number/
要点:字符串比较;数字比较
x<0直接pass,末尾是0直接pass
python可以用str(x)[::-1]直接反转字符串比较
C++中用了vector储存每位数然后循环比较
java用了计算一半反转数的方法,不会溢出

二.Python实现

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

三.C++实现

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        if(x==0) return true;
        vector a;
        while(x){
            a.push_back(x%10);
            x=x/10;
        }
        int num=a.size();
        for(int i=0;i<=num/2;i++)
        {
            if(a[i]!=a[num-1-i]) return false;
        }

        return true;
    }
};

四.java实现

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertx = 0;
        while (x > revertx) {
            revertx = revertx * 10 + x % 10;
            x /= 10;
        }

        return x == revertx || x == revertx / 10;
    }
}

你可能感兴趣的:(LeetCode简单题:9. 回文数(Python,C++,Java))