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.

Follow up:

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

第一次写的效率很低;

Runtime: 10 ms, faster than 59.01% of Java online submissions for Palindrome Number.

Memory Usage: 36.1 MB, less than 63.61% of Java online submissions for Palindrome Number.

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 10 && x >= 0){
            return true;
        }
        if (x < 0 || x % 10 == 0){
            return false;
        }
        int digits  = (int) (Math.log10(x) + 1);//获取数字长度
        int temp = x;
        int high = 0;
        int low = 0;
        for(int digitsIndex = 1;digitsIndex <= digits/2;digitsIndex++){
            high = (x /(int)(Math.pow(10,digits - digitsIndex)))%10;
            low = temp%10;
            if (high != low){
                return false;
            }
            temp /= 10;
        }
        return true;
    }
}

然后就改成官方这种了

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 10 && x >= 0){
            return true;
        }
        if (x < 0 || x % 10 == 0){
            return false;
        }
        int rightHalf = 0;
        while(x > rightHalf){
            rightHalf = rightHalf*10 + x%10;
            x /= 10;
        }
        return rightHalf == x || rightHalf/10 == x;
    }
}

你可能感兴趣的:(LeetCode - 9.Palindrome Number)