牛客题霸 [回文数字(palindrome-number)] C++题解/答案

牛客题霸 [回文数字] C++题解/答案

题解:

首先:负数不可以回文(起码看着就不对称)
然后我们将x翻转,很简单sum=sum*10+x%10;
因为x最终会变成0,所以用y先存一下x
最后比较sum与y是否相等

面试:

class Solution {
public:
    /**
     * 
     * @param x int整型 
     * @return bool布尔型
     */
    bool isPalindrome(int x) {
        // write code here
        if(x<0)return 0;
        int y=x;
        int sum=0;
        while(x){
            sum=sum*10+x%10;
            x/=10;
        }
        return sum==y;
    }
};
posted @ 2020-11-05 11:31  回归梦想  阅读(74)  评论(0编辑  收藏  举报