Palindrome Number

Palindrome Number

Sergei Golitsyn

Given an integer x, return true if x is palindrome integer.

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

  • For example, 121 is a palindrome while 123 is not.

 

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.

Solution:

For this problem, we can prepare a few attractive solutions. The first one will be like brut force solution. We are converting X into a string and then checking characters in the string. We are preparing a few pointers for it, and step by step, check them:

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

Hope it is clear. Also, we add some corner case checks. A negative number cannot be a palindrome.


The next variant is working with digits. We can check digits. Should we check all of them?? Sure no. We can convert only half of them and compare.

I will try to explain it better. We have 121 --> first digit 1 and rest is 12, then we ger dest again --> rest 2, and we add 2 to 1 --> 12. Then we can compare 1 with 12 and 1 with 1. Is it clear?

public boolean isPalindrome(int x) {
  if(x < 0 || (x % 10 == 0 && x != 0)) {
        return false;
      }
      int revert = 0;
     
      while (x > revert){
        int rest = x % 10;
        x /= 10;
        revert = revert * 10 + rest;
    }
    return revert == x || revert/10 == x;

That is a helpful technic to get the last digit in a number and how to iterate over digits.

Report Page