Leetcode 9. Palindrome Number

来源:互联网 发布:c语言float的取值范围 编辑:程序博客网 时间:2024/06/10 15:09

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;    }};





0 0