Palindrome Number

题目链接

Palindrome Number - LeetCode

注意点

  • 负数肯定是要return false的
  • 数字的位数要分奇数和偶数两种情况

解法

解法一:将数字转化为字符串,然后对字符串从中间开始往两边拓展比较,要分长度为奇数和偶数的情况。时间复杂度为O(n)

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0 || (x%10 == 0 && x!=0))
        {
            return false;
        }
        else
        {
            string num;
            while(x != 0)
            {
                num += x%10;
                x /= 10;
            }
            int n = num.length(),left,right;
            if(n%2==1)
            {
                left = n/2;
                right = n/2;
            }
            else
            {
                left = n/2-1;
                right = n/2;
            }
            while(left >= 0&&right <= n)
            {
                if(num[left] == num[right])
                {
                    left--;
                    right++;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }
    }
};

小结

  • 很简单的题没什么好说的,就是不知道前3%的大佬都是怎么做到的...
原文地址:https://www.cnblogs.com/multhree/p/10308663.html