Math-9.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.


題目解析

1. 此題想要判斷一個數字是不是迴文數字。並且要求不能使用額外的輔助空間。即空間複雜度必須是O(1)級別。
2. 思考首先負數有-號,肯定不是迴文。然後可以倒着寫出這個數來判斷與原數是否相等。等於了就是迴文數字。時間複雜度O(n)。


代碼如下:

class Solution 
{
public:
    
    bool isPalindrome(int x) 
    {
        if(x<0 || x!=0 && x%10==0)
        // 如果x是負數或者x是一個10的整數倍的數,那麼x都不可能迴文
            return false;
        
        int sum = 0;
        int xx = x, num = 0;
        while(x > abs(sum) && num++ < 32)
        {
            // 可以倒着計算出sum,來比對最終的sum和x,從而判斷是否迴文;之所以加上num<32,是因爲防止x爲32位最大整數,此時x永遠大於sum,防止陷入死循環。
            sum = sum*10 + xx%10;
            xx = xx/10;
        }
        
        return (x == sum);
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章