9. Palindrome Number

来源:互联网 发布:mac开机密码怎么取消 编辑:程序博客网 时间:2024/06/05 08:33

这道题看起来简单,但是使用反转会使用一个或两个整数,会导致 Memory Limit Exceeded

class Solution {public:    bool isPalindrome(int x) {        int i=x, n=0;        while(i>0)        {            n=i%10+n*10;            i/=10;        }        return n==x;    }    };
class Solution {public:    bool isPalindrome(int x) {        if(x<0|| (x!=0 &&x%10==0)) return false;        int sum=0;        while(x>sum)        {            sum = sum*10+x%10;            x = x/10;        }        return (x==sum)||(x==sum/10);    }};

后来改成这样还是不行:

class Solution {public:    bool isPalindrome(int x) {        //negative number        if(x < 0)            return false;        int len = 1;        while(x / len >= 10)            len *= 10;        while(x > 0)    {            //get the head and tail number            int left = x / len;            int right = x % 10;            if(left != right)                return false;            else    {                //remove the head and tail number                x = (x % len) / 10;                len /= 100;            }        }        return true;    }};

现在还在想这么过,我觉得我做了一道假的 9. Palindrome Number

参考:http://www.cnblogs.com/fanyabo/p/4183006.html

0 0
原创粉丝点击