Palindrome Number
A number is a palindrome when it reads the same from left to right and from right to left.
121 is a palindrome. 123 is not, because backwards it reads 321.
A negative number is never a palindrome: -121 read backwards is 121-.
Try to solve it without turning the number into a string: build the reversed number digit by digit and compare.
Write a function named isPalindrome that gets an integer x and returns true if x is a palindrome, and false otherwise.
Constraints: -2^31 <= x <= 2^31 - 1
Function
- arg1integer
- Returnsboolean
Examples
- Input
- arg1 = 121
- Output
- true
- Input
- arg1 = -121
- Output
- false
+8 hidden tests on Submit
Hints
Open them one at a time. Each one gives away a little more.
Negative numbers can never be palindromes, so handle them first.
Take the last digit with
x % 10and drop it with integer division by10.Build the reversed number with
reversed = reversed * 10 + digit, then compare it with the original.
A full walkthrough of this problem is on its way.
Similar problems
Problems that use the same ideas. Solving two or three of them is what makes a pattern stick.
Python
def isPalindrome(x):
# Write code hereCase 1
Case 2
Input
arg1 = 121
Expected
true