LeetCode從零刷起 (9. Palindrome Number)

LeetCode(9. Palindrome Number)

Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

知識(shí)點(diǎn):

  1. 負(fù)數(shù)不會(huì)是回文。
  2. 由于本題要求"Do this without extra space",在我理解為空間復(fù)雜度應(yīng)該控制在O(1)。所以本題不能用string類型轉(zhuǎn)換來(lái)做。

解題思路:

本題是判斷一個(gè)integer是否為回文。我的做法是,從integer的兩邊開(kāi)始往中間走來(lái)判斷,設(shè)置一個(gè)left變量和一個(gè)right變量。當(dāng)最后剩余的數(shù)據(jù)位數(shù)小于等于二的時(shí)候,進(jìn)行一下簡(jiǎn)單的判斷就可以了。
C++代碼如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false; //negative number is not a palindrome
        if (x >= 0 && x <= 9) return true;
        //to get the length of digits
        int len = 0, x1 = x;
        while (x1 > 0){
            len++;
            x1 /= 10;
        }
        //from head and from tail to check
        int left, right;
        while (len > 2){
            left = x / pow(10,len-1);
            right = x % 10;
            if (left != right)
                return false;
            x = (x - left*pow(10,len-1)) / 10;
            len -= 2;
        }
        if (len == 1)
            return true;
        else{ // len == 2
            if (x/10 == x%10)
                return true;
            else 
                return false;
        }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,916評(píng)論 0 33
  • 我從iOS5開(kāi)始編寫(xiě)iOS的應(yīng)用,應(yīng)該算是起步比較晚的了。那個(gè)時(shí)候我大二,因?yàn)橛X(jué)得學(xué)院所教的用swing寫(xiě)的PC客...
    danisfabric閱讀 2,093評(píng)論 3 11
  • 第九章 你的出現(xiàn) 李教練:今天我們介紹一位新同學(xué)唐南,馬上就要去新加坡當(dāng)教練了,同學(xué)們多像他學(xué)習(xí),好自己訓(xùn)練吧!...
    吖吖唅閱讀 163評(píng)論 0 0
  • 我們每個(gè)人都有心情不好的時(shí)候,怎么去解決呢? 心情不好,心里壓抑,讓我們來(lái)?yè)Q一個(gè)思維方式,就是身體內(nèi)於堵了,就如同...
    開(kāi)心的靈通閱讀 504評(píng)論 1 1
  • 講真,一直不明白老家方言里的zuxie,究竟普通話里哪兩個(gè)字可指,直到初中學(xué)習(xí)魯迅先生的《社戲》,“做社”二字躍于...
    十二月的白菜閱讀 2,313評(píng)論 10 15

友情鏈接更多精彩內(nèi)容