9. Palindrome Number

题目描述:

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

Example 1:

Input:num = 1221
Output: true

Note:

  1. Suppose negative integers is not palindrome

题目翻译

判断一个整数是不是回文,在判断过程中不要使用额外空间。

示例1:

输入: num = 1001221001
输出: true

注意: NULL

解题方案

标签: Math

思路1:

  • 我们假设负数不是回文,以及int变量不属于额外空间
  • 我们很容易想到一种方法,它贴近于我们日常判断回文的方法,一次判断对应的两位,即逐位判断

代码:

class Solution {
    public:
    bool isPalindrome(int num)
    {
        if (num<0)
          return false;
        int base=1;
        while (num/base >= 10)
            base *= 10;
        while (num!=0)
        {
            if (num/base != num%10)
                return false;
            num=(num%base) / 10;
            base /= 100;
        }
        return true;
    }     
}

思路2:

  • 首先,经过了昨天的反转习题,看到今天这道题我们很容易想到,将整数(以下记为A)反转,然后进行比较即可。记整数长为n,时间复杂度为O(n)
  • 这里参考了discuss中的一个代码,因为它有一个相较不错的避免溢出的方法

    代码:

    bool isPalindrome(int num)
    {
     if(num < 0)
         return false;
     int temp1 = num;
     int temp2 = 0;
     while(temp1 >= 10)
     {    
         temp2 *= 10;
         temp2 += temp1%10;
         temp1 /= 10;
     }
     return temp2 == num/10 && temp1 == num%10;
    }
    

参考资料

results matching ""

    No results matching ""