Palindrome Number- LeetCode

Problem Statement

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.

Intuition

class Solution {
public boolean isPalindrome(int x) {
int num = x;
boolean flag = false;
if (x < 0 || (x % 10 == 0 && x != 0)) return flag;
long r = 0;
while (x > 0) {
r = r * 10 + x % 10;
x /= 10;
}
if (r == num) {
flag = true;
return flag;
}
return flag;
}
}
view raw palindrome.java hosted with ❤ by GitHub

Complexity Analysis

  • Time complexity : O(log10​(n)). We divided the input by 10 for every iteration, so the time complexity is O(log10​(n))
  • Space complexity : O(1)

Explanation

First of all we should take care of some edge cases. All negative numbers are not palindrome, for example: -123 is not a palindrome since the ‘-‘ does not equal to ‘3’. So we can return false for all negative numbers.

Now let’s think about how to revert the last half of the number. For number 1221, if we do 1221 % 10, we get the last digit 1, to get the second to the last digit, we need to remove the last digit from 1221, we could do so by dividing it by 10, 1221 / 10 = 122. Then we can get the last digit again by doing a modulus by 10, 122 % 10 = 2, and if we multiply the last digit by 10 and add the second last digit, 1 * 10 + 2 = 12, it gives us the reverted number we want. Continuing this process would give us the reverted number with more digits.

Feel free to post queries.

Leave a comment

Design a site like this with WordPress.com
Get started