1. 程式人生 > >Leetcode 9. Palindrome Number -- 判斷輸入的整數是否是迴文數字

Leetcode 9. 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.

方法:

/**
 * <p>Title: </p>
 * <p>Description: </p>
 *
 * @Author 
 * @CreateTime 2019/1/12 10:19
 */
public class Leetcode_9_PalindromeNumber {

    public static void main(String[] args) {
        Leetcode_9_PalindromeNumber leetcode_9_palindromeNumber = new Leetcode_9_PalindromeNumber();
//        System.out.println(leetcode_9_palindromeNumber.isPalindrome(12321));
        System.out.println(leetcode_9_palindromeNumber.isPalindrome(23432));
    }

    /**
     * 優化
     * 思路:x從右往左計算出一個新的數值q,如果q==x則返回true,反之不是迴文數字
     * Runtime: 153 ms, faster than 75.02% of Java online submissions for Palindrome Number.
     *
     * @param x
     * @return
     */
    public boolean isPalindrome(int x) {
        int p = x, q = 0;//p是從右往左用來計算的,q是結果
        while (p >= 1) {
            q *= 10;
            q += p % 10;
            p /= 10;
        }
        return q == x;
    }

    /**
     * https://leetcode.com/problems/palindrome-number/discuss/5188/O(1)-space-O(lgn)-time-java-solution-no-overflow-risk
     * Runtime: 158 ms, faster than 61.99%
     *
     * @param x
     * @return
     */
    public boolean isPalindrome3(int x) {

        if (x < 0) return false;

        int p = x;
        int q = 0;
        while (p >= 10) {
            q *= 10;
            q += p % 10;
            p /= 10;
        }
        return q == x / 10;
    }


    /**
     * 檢測是否是迴文數字
     * Runtime: 177 ms, faster than 24.77%
     *
     * @param x
     * @return
     */
    public boolean isPalindrome2(int x) {
        if (x < 0) {
            return false;
        }
        if (x >= 0 && x <= 9) {
            return true;
        }
        String num = x + "";
        int length = num.length();
        int halfLength = length / 2;
        for (int i = 0; i < halfLength; i++) {
            if (num.charAt(i) != num.charAt(length - 1 - i)) {
                return false;
            }
        }
        return true;
    }//isPalindrome
}

end