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

Palindrome Number

时间:2014-11-15 09:58:31      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   使用   sp   

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

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.

思路:首先,如果输入的数字为负数,判断为非回文。

   求出给出的数字的位数相同的最小值,用i(i一定要声明为长整型,不然会溢出,出现超时)记录(注意此时求的时候要将i等于x的等号加上,以防i==x)

   然后分别求出最高位和最低位进行比较,求最高位的方法就是使用x/i,然后x%i将最高位消除,取次高位,依次类推。取低位的方法就是先取模,然后除以1*10*10...,取倒数第一位,倒数第二位。。。

C++实现代码:

#include<iostream>
using namespace std;

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)
            return false;
        long long i=1;
        while(i<=x)
        {
            i*=10;
        }
        i=i/10;
        long long j=10;
        while(j<=i)
        {
            if(x/i!=(x%j)/(j/10))
                return false;
            x=x%i;
            i/=10;
            j*=10;
        }
        return true;
    }
};

int main()
{
    Solution s;
    cout<<s.isPalindrome(1001)<<endl;
}

运行结果:

bubuko.com,布布扣

Palindrome Number

标签:style   blog   http   io   color   ar   os   使用   sp   

原文地址:http://www.cnblogs.com/wuchanming/p/4098794.html

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