[9] Palindrome Number

Updated on in LeetCode with views and comments
本文最后更新于 408 天前,其中的信息可能已经不够准确,请您酌情参考!

题目

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?

解法

思路

求出回文数,进行比较

代码

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        if (x < 10) {
            return true;
        }
        List<Integer> list = new ArrayList<>();
        int y = x;
        while (y >= 10) {
            list.add(y % 10);
            y = y / 10;
        }
        list.add(y);
        long z = 0l;
        for (int i : list) {
            z = z * 10 + i;
        }
        if (x == z) {
            return true;
        }
        return false;
    }
}

Runtime

7 ms
Beats 19.03% of users with Java

二 转成String判断

代码

class Solution {
    public boolean isPalindrome(int x) {
        String str = String.valueOf(x);
        int len = str.length();
        for(int i = 0; i < len / 2; i++) {
            if(str.charAt(i) != str.charAt(len - 1 - i)) {
                return false;
            }
        }
        return true;
    }
}

Runtime

6 ms
Beats 37.15% of users with Java