Palindrome Number--LeetCode

来源:互联网 发布:2015网络流行词大全 编辑:程序博客网 时间:2024/06/05 12:42

Palindrome Number

(原题链接:点击打开链接)

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.

Solution:

判断回文数字,首先排除负数。然后根据回文的对称的特点我们可以从前后两端向中间一直判断是否对称。下面方法是先得到x的位数,然后根据求余整除得到每一位的数字,然后比较。时间复杂度为O(N)(N为x位数),可是设计大量的计算。
class Solution {public:    bool isPalindrome(int x) {        if(x < 0) return false;        int i = 0;        for(i; ;i++)        {            if(x / (int)pow(10,i) < 10) break;        }        i++; //i is the digital length of x        cout<<i<<endl;        for(int a = 0; a <= (i-1)/2; a++)        {            if(x % (int)pow(10, i - a) / (int)pow(10, i-a-1) != x % (int)pow(10, a + 1) / (int)pow(10, a)) return false;        }        return true;    }};

方法二:将数据进行翻转,由于翻转之后会造成溢出,所以将翻转后数据范围扩大
class Solution {public:    bool isPalindrome(int x) {        if(x < 0) return false;        int y = x;        long long int z = 0;        int i = 0;        while(y != 0)        {            z = z * 10 + y % 10;            y = y / 10;        }        return x == z;    }};

方法三:对方法二进行优化。方法二对整个数进行了翻转,我们可以考虑只翻转这个数的后半部分然后和前半部分比较
class Solution {public:    bool isPalindrome(int x) {        if(x < 0 || (x != 0 && x % 10 == 0)) return false;        int z = 0;        while(x > z)        {            z = z * 10 + x % 10;            x = x / 10;        }        return x == z || z / 10 == x;    }};