1. 程式人生 > 其它 >力扣刷題:9. 迴文數

力扣刷題:9. 迴文數

技術標籤:leetcodeleetcodec++字串

題目要求

給你一個整數 x ,如果 x 是一個迴文整數,返回 ture ;否則,返回 false 。

迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。例如,121 是迴文,而 123 不是。

在這裡插入圖片描述

在這裡插入圖片描述
原題連結

版本一:轉換成字串處理

class Solution {
public:
    bool isPalindrome(int x) {
            string s = std::to_string(x);
        if (s == string(s.crbegin(), s.crend()))
        {
return true; } return false; } };

整體思路

很簡單。將傳入的int整數轉換成string型別,然後再判斷string和自身的倒置是否相等。

版本二:非字串版本

class Solution {
public:
    bool isPalindrome(int x) {
         int temp = x, invertInt = 0;
        if (x < 0)
        {
            return false;
        }
        while
(x != 0) { if(invertInt >= static_cast<int>(pow(2,31)/10) - x % 10) return false; invertInt = invertInt * 10 + x % 10; x = x / 10; } if (temp == invertInt) { return true; } return false;
} };

整體思路

傳入一個整數,每次將該整數的最後一位提取出來,然後傳入到invertInt的最後一位。傳入完畢後對比前後兩個數,如果相等,則是迴文字數。(類似於棧的pop和push)

需要注意的是,在將整數的最後一位傳給invertint的的最後一位時,有可能會出現超出int型別的限制(int表示的範圍參考第8題)。所以需要加一個if判斷來判斷是否超界。

學到了什麼

1、再次強化了int能夠表達的數的範圍的印象:[-pow(2,31), pow(2,31)-1]
2、超出int型別的限制這個執行時異常在VS裡不會報錯?