第二週Palindrome Number迴文數

Palindrome Number迴文數

Leetcode algorithms problem 9:palindrome number

  • 問題描述

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

  • 問題提示

    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.負數不是迴文數,如-123 != 321-,所以當輸入的x < 0時直接false就好。
    2.第一想到的解決方案就是將數字轉換成字符串,再反轉字符串來比較,但這樣佔用太多空間,題目要求空間複雜度爲O(1),所以不行。
    3.觀察迴文數的特點,發現首尾2個數字一定相同,於是想到每次都提取首尾2個數,比較它們,不一樣就return false,一樣就剔除它們,再提取縮小的x的首位數,重複比較,直到x<0。

代碼

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

時間複雜度: O(logn)
空間複雜度: O(1)


收穫&雜談

第一次在leetcode上面刷題 英文太弱提示還得翻譯,一個學期沒敲代碼題,對數字函數都不敏感了,在提取數字的時候老是出亂子,% 和/用反什麼的,加上leetcode禁止重複提交,需要等待。
leetcode提供用來debug的主函數,少了自己去編寫的時間,挺方便的,還提供解決方法,還有討論,很棒。

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