码迷,mamicode.com
首页 > 其他好文 > 详细

#9 Palindrome Number

时间:2015-04-11 20:39:13      阅读:115      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!