LeetCode9-Palindrome Number(C++)

Description

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

AC代碼

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int y = 0, z = x;
        short int n=0;
        while(z != 0) {
            n = z % 10;
            // 這一步是因爲要確保 y*10 +n < INT_MAX
            if(y > ((INT_MAX - n)/10)) return false;
            y = y*10 + n;
            z = z/10;
        }
        return (x==y);
    }
    // 這個函數僅僅是用來測試方便,提交的時候也可以不加
    void judgeResult(int x) {
        if(isPalindrome(x)) {
            cout << x << " is palindrome" <<endl;
        } else {
            cout << x << " is not palindrome" <<endl;
        }
    }
};

測試代碼

int main() {
    Solution s;
    s.judgeResult(-121);
    s.judgeResult(121);
    s.judgeResult(456);
    s.judgeResult(567898765);
}

測試結果

-121 is not palindrome
121 is palindrome
456 is not palindrome
567898765 is palindrome

總結

前面有類似的題目,是判斷字符串是否是迴文字符串,這道題的描述裏面說了在解題時應避免先轉換成字符串再做迴文。以上的AC代碼實際上是利用了之前某一道題目裏面的反轉字符串,然後判斷字符串反轉後是否還與本身相等。

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