LeetCode从零刷起 (9. Palindrome Number)

LeetCode(9. 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.

知识点:

  1. 负数不会是回文。
  2. 由于本题要求”Do this without extra space”,在我理解为空间复杂度应该控制在O(1)。所以本题不能用string类型转换来做。

解题思路:

本题是判断一个integer是否为回文。我的做法是,从integer的两边开始往中间走来判断,设置一个left变量和一个right变量。当最后剩余的数据位数小于等于二的时候,进行一下简单的判断就可以了。
C++代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false; //negative number is not a palindrome
        if (x >= 0 && x <= 9) return true;
        //to get the length of digits
        int len = 0, x1 = x;
        while (x1 > 0){
            len++;
            x1 /= 10;
        }
        //from head and from tail to check
        int left, right;
        while (len > 2){
            left = x / pow(10,len-1);
            right = x % 10;
            if (left != right)
                return false;
            x = (x - left*pow(10,len-1)) / 10;
            len -= 2;
        }
        if (len == 1)
            return true;
        else{ // len == 2
            if (x/10 == x%10)
                return true;
            else 
                return false;
        }
    }
};
    原文作者:CopyYoung
    原文地址: https://www.jianshu.com/p/d28b44da1cd7
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞