Leetcode 9. Palindrome Number

Determine whether an integer is a palindrome.Do this without extra space.

回文数:1.负数不是回文数;2.逆序和正序表示的数字相同。

solution 1:(with extra space.

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        vector<int> num;
        for(int i=0;x!=0;i++){
            num.push_back(x%10);
            x=x/10;
        }//把x每位单独分离,逆序存储在num
        int len=num.size();
        for(int i=0;i<len;i++){
            if(num[i]!=num[len-1-i]) return false;
        }
        return true;
    }
};

solution 2:(without extra space)

<pre name="code" class="cpp">class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        int s=0;int y=0;
        while(x!=0){
            s=x%10;
            x=x/10;
            y=y*10+s;
        }
        if(x==y) return true;
        return false;
    }
};
//答案始终不对,因为y的值正确,但是x的值已经改变

 
 
<pre name="code" class="cpp">class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        int xx=x;
        int s=0;int y=0;
        while(x!=0){
            s=x%10;
            x=x/10;
            y=y*10+s;
        }
        if(xx==y) return true;
        return false;
    }
};


 
 




你可能感兴趣的:(Leetcode 9. Palindrome Number)