美文网首页
[leetcode] 9. Palindrome Number

[leetcode] 9. Palindrome Number

作者: Kevifunau | 来源:发表于2018-10-02 22:42 被阅读0次

回文数字

首先 负数 ‘-x’ 肯定不是 palindrome

这题就是用 数字反转

e.g. 123 --> 321
ans = ans*10 + x%10

ans x
0*10 + 123%10 = 3 123/10 = 12
3*10 + 12%10 = 32 12/10 = 1
32*10 + 1%10 = 321 1/10 = 0
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return 0;
        
        int origin = x;
        int ans = 0;

        while(x){
            ans = ans*10 + x%10;
            x = x/10;  
        }
        return origin==ans;

    }
};
image.png

当然 可以用python赖皮 ........(逃

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        return str(x) ==str(x)[::-1]

相关文章

网友评论

      本文标题:[leetcode] 9. Palindrome Number

      本文链接:https://www.haomeiwen.com/subject/sdnaoftx.html