1. 程式人生 > >[Java] Palindrome Number

[Java] Palindrome Number

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.

Follow up: Coud you solve it without converting the integer to a string?

這道題還算簡單,有以下幾個點需注意:

  1. 負數不是回數,所以只要是負數直接返回false。
  2. 對正數進行反轉操作,判斷是否於原數相同,相同即為回數。

程式碼如下:

class Solution {
    public boolean
isPalindrome(int x) { if(x<0) return false; int temp = x; int ret = 0; while(temp!=0){ int mod = temp%10; temp = temp/10; ret = ret*10 + mod; } if(ret == x) { return true; }else{ return false
; } } }

不過上面的程式碼沒有考慮溢位的問題,不知道為啥提交居然過了。接下來寫一種不用考慮溢位的方法,就是取出這個數的第一個數字和最後一個數字比較,然後掐頭去尾,比較剩下的。

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0) return false;
        int div = 1;
        while(x/div>=10){
            div*=10;
        }
        while(x>0){
            int first = x/div;
            int last = x%10;
            if(first != last){
                return false;
            }
            x=(x%div)/10;//掐頭去尾
            div/=100;//去了兩位數,div也要跟著變

        }
        return true;
    }
}