Categories
All 算法

做題筆記:Palindrome Number (Java)

題目描述:

給定一個整數 x,如果 x 是回文數,則返回 true

回文數指一個整數向後讀和向前讀内容相同。

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

算術解法:

利用 Java 整數倒序計算:

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        
        int ori = x;
        int p = 0;
        while (ori != 0) {
            p = p * 10 + ori % 10;
            ori /= 10;
        }
        
        return x == p;
    }
}

9 ms,超過 87.67% 的答案。

轉換為 String 的解法:

進階要求 Follow Up 竟然問了一句 Could you solve it without converting the integer to a string? 原來我想到的已經是進階方法了,常規解法是轉換為 String:

class Solution {
     public boolean isPalindrome(int x) {
         char[] nums = String.valueOf(x).toCharArray();
         int start = 0;
         int end = nums.length-1;
         while(start < end) {
             if(nums[start] != nums[end]) return false;
             start++; end--;
         }
        return true;
    }
}

19 ms,超過 19.48% 的答案。

Leave a Reply

Your email address will not be published. Required fields are marked *