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

【Palindrome Number】cpp

时间:2015-06-06 10:27:42      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

代码:

class Solution {
public:
        bool isPalindrome(int x)
        {
            if (x<0) return false;
            return x==Solution::reverse(x);
        }
        static int reverse(int x)
        {
            int ret = 0;
            while (x)
            {
                if ( ret>INT_MAX/10 || ret<INT_MIN/10 ) return 0;
                ret = ret*10 + x%10;
                x = x/10;
            }
            return ret;
        }
};

tips:

1. 如果是负数,认为不是回文数

2. 如果是非负数,则求这个数的reverse,如果等于其本身就是回文数,否则就不是。

利用的就是reverse integer这道题(http://www.cnblogs.com/xbf9xbf/p/4554684.html)。

====================================

还有一种解法可以不用reverse,有点儿类似求字符串是否是回文的题目(头尾两个指针往中间夹逼)。

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

对于这道题的整数来说,就是找到给定整数的最大位数-1,即d。

每次从高位取一个数,从低位取一个数;然后,再把高低位都去掉获得新数(x=x%d/10);这样照比上一次的数少了两位,因此还有d=d/100。

【Palindrome Number】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4556064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!