[leetcode]33 Palindrome Number

题目链接:https://leetcode.com/problems/palindrome-number/
Runtimes:131ms

1、问题

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

2、分析

删除回文,传统思路是按照顺序将数字存入数组,然后进行字符串回文检查。但是问题要求不要有额外空间,想了想也是可以实现的,只要能取到头尾两个数字即可。

3、总结

陷阱:1、负数都不是回文串;2、边界检查,如int最大值1874994781;3、条件判断的选择x / c >= 10,之前傻傻的选了减法,即x - c < c.

4、实现

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0)
            return false;
        if (x < 10)
            return true;
        int c = 10;
        while (x / c >= 10)
        {
            c *= 10;
        }
        int a = 10;
        while (c > 0)
        {
            if (x % 10 != x / c)
                return false;
            x %= c;
            x /= 10;
            c /= 10;
            c /= 10;
        }
        return true;
    }
};

5、反思

待改进。

你可能感兴趣的:(LeetCode,number,palindrome)