[leetcode] Palindrome Number(不使用额外空间)

本来推断回文串是一件非常easy的事情,仅仅须要反转字符串后在与原字符串相比較就可以。这道题目明白说明不能使用额外的空间。那么使用将其分解连接成字符串的方法便不是可行的。仅仅好採用数学的方式: 每次取最高位和最低位相比較,总的位数能够用一个while先处理出来,循环直至取余和除数相等。

详细见代码:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)       //special due 
            return false;
        if(x<10)
            return true;
        int curMod=0;
        int test=x;
        while(test)
        {
             curMod++;
             test/=10;
        }
        curMod--;// bit num 
        int left=pow(10,curMod*1.0),right=10;
        while(right<=left)
        {
                if(x%right!=x/left)
                        return false;
                x=x%left,x/=10;
                left/=100;
        }
        return true;
    }
};


posted @ 2017-06-09 13:05  brucemengbm  阅读(226)  评论(0编辑  收藏  举报