每天一道leetcode-判斷回文整數(shù)

題目描述

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.

想法

  • 想法一:把整數(shù)轉(zhuǎn)換成字符串然后從中心往兩邊依次判斷
  • 想法二:把整數(shù)轉(zhuǎn)過(guò)來(lái),但是這會(huì)有一個(gè)問(wèn)題就是反過(guò)來(lái)的數(shù)可能超過(guò)了int的范圍
  • 想法三:把整數(shù)的后半部分轉(zhuǎn)過(guò)來(lái),跟前半部分進(jìn)行比較,那么這里就有一個(gè)問(wèn)題就是如何判斷整數(shù)已經(jīng)到了一半,那就是從后面拿數(shù)拿出來(lái)的數(shù)比拿掉后的大了就已經(jīng)達(dá)到了一半

代碼

public boolean isPalindrome(int x) {
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber/10;
//可能是奇數(shù)也可能偶數(shù)
    }
?著作權(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)容

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