LeetCode - Palindrome Number

1 minute read

Problem description

description

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

1
2
Input: 121
Output: true

Example 2:

1
2
3
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:

1
2
3
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

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

Analysis

Basic idea is to convert Integer to digits and use two pointer to compare them one by one, beats 41.68%.

Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class PalindromeNumber {
  public boolean isPalindrome(int x) {
    if (x < 0) {
      return false;
    }

    if (x < 10) {
      return true;
    }

    List<Integer> digits = new ArrayList<>();

    while (x != 0) {
      digits.add(x % 10);
      x = x / 10;
    }

    int i = 0, j = digits.size() - 1;

    while (i <= j){
      if (digits.get(i++) != digits.get(j--)){
        return false;
      }
    }

    return true;
  }
}

A more simple way is to reverse the number and check if they are equal, with some edge cases to deal with.

Here’s the code from LeetCode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber / 10; // here to deal with the odd and even part
    }
}

A tricky skill here is that we don’t need to reverse all of x, just half of the x is enough.

What to improve

  • think about efficiency