LeetCode 9 — Palindrome Number(迴文數)

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?

翻譯
判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。

示例 1:
輸入: 121
輸出: true
示例 2:
輸入: -121
輸出: false
解釋: 從左向右讀, 爲 -121 。 從右向左讀, 爲 121- 。因此它不是一個迴文數。
示例 3:
輸入: 10
輸出: false
解釋: 從右向左讀, 爲 01 。因此它不是一個迴文數。
進階:
你能不將整數轉爲字符串來解決這個問題嗎?

分析
轉化爲字符串,倒置字符串若與原來相同,返回true。

c++實現

class Solution {
public:
    string reverse(string s) {
        for (int i = 0; i <= (s.length()-1)/2; i++)
        {
            char tmp = s[i];
            s[i] = s[s.length()-1-i];
            s[s.length()-1-i] = tmp;
        }
        return s;
    }
    
    bool isPalindrome(int x) {
        stringstream ss;
        ss << x;
        string s = ss.str();
        string S = reverse(s);
        for (int i = 0; i < S.length(); i++)
        {
            if (S[i] != s[i])
                return false;
        }
        return true;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章