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
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.