LeetCode系列9:迴文數

題目

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

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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/palindrome-number
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解題源碼

轉換字符串
class Solution {
public:
    bool isPalindrome(int intA) {
		string strA = to_string(intA);
		string strRe;
		bool IsPalindrome = true;
		
		for (int i = strA.size()-1; i >=0; i--)
		{
		 	 strRe += strA.at(i);
		}
		
		return strA == strRe;
    }
};

在這裏插入圖片描述

數學法比較
class Solution {
public:
    bool isPalindrome(int intA) {
      bool blnRe = false; 
    if (intA < 0 || (intA != 0 && intA % 10 == 0))
    {
        return blnRe;
    } 
    int intReverse = 0;

    while (intA > intReverse)
    {
        intReverse = intReverse * 10 + intA % 10;
        intA /= 10;
    }
	// 會出現奇偶數情況,需要另外單獨判斷。
    return blnRe = (intA == intReverse) || (intA == intReverse / 10);
    }
};

在這裏插入圖片描述

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