leetcode笔记:Palindrome Number

一. 题目描述

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.

二. 题目分析

该题的大意是,判断一个整数是否为回文数。该题给出了很多提示。其中包括要求空间复杂度只能是O(1),所以不能考虑把整数转化为字符串然后reverse比较的方法。

另外,如果使用reverse integer一题的方法,可能会造成数据溢出的问题,所以也是不可行的。

这里的思路也比较简单,每次取出整数的最高位和最低位进行比较,如果相等,去掉这两位,继续比较整数的最高位和最低位,知道整数为0为止。

三. 示例代码

#include <iostream>

using namespace std;

class Solution
{
public:
    bool isPalindrome(int x) 
    {
        if (x < 0) return false;
        int SIZE = 1;
        // 以下操作用于确认x的最高位
        while (x / SIZE >= 10) SIZE *= 10;
        while (x > 0)
        {
            int left = x / SIZE;
            int right = x % 10;
            if (left != right) return false;
            // 去除x的最高位和最低位
            x = x % SIZE / 10;
            SIZE /= 100; // 位数减2
        }
        return true;
    }
};

四. 小结

这并不算高效的方法,提交后发现有耗时更少的方法,只能继续研究了。

你可能感兴趣的:(LeetCode,Algorithm,算法,String,palindrome)