You are given a whole number x. Return true if it reads the same from left to right as it does from right to left, and false if it does not.
A minus sign counts as part of how the number is written, so a negative number cannot read the same both ways.
Example 1
Input: x = 4554 Output: true Why: 4554 backwards is 4554
2 more examples and the constraints
Example 2
Input: x = -323 Output: false Why: backwards it would be 323-
Example 3
Input: x = 120 Output: false Why: backwards it would be 021
Constraints
- x fits in a 32-bit signed integer: from −2,147,483,648 to 2,147,483,647
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Compare the textO(d)
- Reverse half the numberO(d)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 10-digit number | Verdict |
|---|---|---|---|
| Compare the text | O(d) | Passes; uses a string | |
| Reverse half the number | O(d) | Best; half the digits, no string |
d = number of digits in x (at most 10).
Edge cases to test
- Negative numbers. −323 is false because of the minus sign.
- Ends in 0. 120 and 10 are false; 0 on its own is true.
- Odd length. 12321 stops with x = 12 and half = 123; compare 12 with 123 / 10.
- Single digit. Any of 0 to 9 is a palindrome.
- Near the limit. 2,147,483,647 reversed in full overflows an int; the half method never does.
Common mistakes
- Reversing the whole number in a 32-bit int, which overflows for large inputs.
- Forgetting the trailing-zero guard, so 10 comes out as true.
- Comparing only x == half and missing palindromes with an odd number of digits.
How to talk through it
- 1Clarify. Do negatives count as palindromes? Can I convert to a string, or should I avoid it?
- 2Give the string version. Compare the text with its reverse; O(d), but uses extra space.
- 3Avoid the overflow. Reversing the full number can overflow, so reverse only the back half.
- 4Code the half reverse. Guard negatives and trailing zeros, loop while x > half, handle the odd middle digit.
- 5Test out loud. Run 4554, 12321, 10, 0 and a negative before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?