天天看點

【leetcode】9-回文數【C++】

題目如下:

【leetcode】9-回文數【C++】

解題思路:

将該數反過來排一遍如果與之前的數相同即為回文數,注意 負數 與 0 可直接處理。

代碼如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) //負數不為回文數
            return false;
        else if(x == 0) //0為回文數
            return true;
        long a = 0; //轉換時可能存在數組溢出的情況,是以需要長整型
        int temp = x;
        while(temp){
            a = a*10 + temp%10;
            temp = temp / 10;
        }
        if(a == x)
            return true;
        else
            return false;
    }
};