Reads the same backwards
EasyStuck?
Show a hintHide the hint
Reverse the number and compare it with the original. Keep a copy first, because the loop destroys the value it works on.
The ideas behind this problem
Next in this lesson
Turn the digits aroundSay whether a whole number reads the same forwards and backwards. 1221 does. 123 does not.
Worked example#
The simplest correct method uses the reversal you already know: reverse the number and compare it with the original.
For 1221:
| digit taken | what is left | reversed so far |
|---|---|---|
| 1 | 122 | 1 |
| 2 | 12 | 12 |
| 2 | 1 | 122 |
| 1 | 0 | 1221 |
1221 equals 1221, so it is a palindrome.
For 123 the reversal is 321, which is not 123.
Keep a copy of the original before the loop. The loop destroys n on its way to zero, so comparing against n afterwards compares 1221 with 0 and every number fails.
A faster way, and why it is fiddly#
You can reverse only the second half and compare it with the first, stopping when the reversed part is at least as large as what remains. It does half the work and it has an awkward case: an odd number of digits leaves a middle digit that belongs to neither half and must be discarded before comparing.
Worth knowing. Not worth starting with.
Negative numbers#
A negative number is never a palindrome here, because -121 reversed reads 121-, which is not a number. The constraints keep the input at zero or above, so there is nothing to handle, but it is the first thing an interviewer asks.
Constraints#
0 <= n <= 2000000000
Input
n is one whole number.
Output
true or false.
Examples
Input
1221
Output
true
Reversed it is still 1221.
Input
123
Output
false
Reversed it is 321.
Input
0
Output
true
A single digit reads the same either way.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.