首页 > 其他 > 详细

#9 Palindrome Number

时间:2015-04-11 20:38:34      阅读:102      评论:0      收藏:0      [点我收藏+]

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

看到题目第一想法是将数字倒过来相减,看是否为0,但是会超时。原因是大部分可能并不是,所以循环中间就退出循环了。目前这个程序是按最左位与最右位逐次比较。

代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0)
            return false;
        if (x == 0)
            return true;
            
        int base = 1;
        while(x / base >= 10)
            base *= 10;
            
        while(x)
        {
            int leftDigit = x / base;
            int rightDigit = x % 10;
            if (leftDigit != rightDigit)
                return false;
            
            x -= base * leftDigit;
            base /= 100;
            x /= 10;
        }
        
        return true;
    }
};

 

#9 Palindrome Number

原文:http://www.cnblogs.com/Scorpio989/p/4418293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!