设为首页 加入收藏

TOP

[leetcode] Palindrome Number(不使用额外空间)
2015-07-22 20:10:14 来源: 作者: 【 】 浏览:7
Tags:leetcode Palindrome Number 使用 额外 空间

本来判断回文串是一件很容易的事情,只需要反转字符串后在与原字符串相比较即可。这道题目明确说明不能使用额外的空间,那么使用将其分解连接成字符串的方法便不是可行的。只好采用数学的方式: 每次取最高位和最低位相比较,总的位数可以用一个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;
    }
};


?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇poj 1845 Sumdiv (算术基本定理求.. 下一篇uva 673 Parentheses Balance

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: