leetcode 9 Palindrome Number

题目描述:

https://leetcode.com/problems/palindrome-number/

leetcode 9 Palindrome Number

AC代码:

class Solution {
public:
    bool isPalindrome(int x) {
        int t=0;
        //如果x为负数、不等于零但只有一位,直接返回false
        if(x < 0 || x % 10 == 0 && x !=0)
            return false;
        
        //翻转
        while(x > t){
            t = t*10 + x % 10;
            x /=10;
        }
        //如果是回文数返回true,否则返回false
        return x == t || x == t / 10;
        //return p ;
    }
};
 
int main()
{
    Solution  s;
    int x = 121;
    bool res = s.isPalindrome(x);
    cout<<res<<endl;
    return 0;
}
 

一开始简单的将数进行翻转,然后和原数进行比较,结果提示溢出,最后才看到题目在最下面的Hide Hint已经提示过了,(⊙﹏⊙)


leetcode 9 Palindrome Number

 
//虽然可以得出结果,但是会造成溢出
class Solution {
public:
    bool isPalindrome(int x) {
        bool p;
        int t=0;
        int r = x;
        //如果x为负数、不等于零但只有一位,直接返回false
        if(x < 0 || x % 10 == 0 && x !=0)
            return false;
        //翻转
        while(r > 0){
            t = t*10 + r % 10;
            r /=10;
        }
        //如果是回文数返回true,否则返回false
        return (x == t) ? true : false ;
    }
};