Palindrome Number
The key insight: a number is a palindrome if and only if reversing its digits mathematically produces the same value. We can reverse a number without string conversion by repeatedly extracting the last digit with x % 10 and discarding it with Math.floor(x / 10), building the reversed number digit by digit. Once reversed, we compare it to the original — if they match, the number reads the same forward and backward.
Details
Animated on: Given an integer x, determine if it's a palindrome by reversing its digits using mod and divide (no string conversion).
Problem:Palindrome NumberEasy
Math
step 1 / 10
original = x = 121. We'll reverse x digit by digit, storing the result in reversed.
- x=0· arr[0] = 121
1FUNCTION isPalindrome(x):2 IF x < 0: RETURN false3 original = x4 reversed = 05 WHILE x > 0:6 digit = last digit of x (x mod 10)7 reversed = reversed * 10 + digit8 drop the last digit of x (integer divide x by 10)9 RETURN true if reversed equals original, otherwise false
← / → step · space play · Home restart
Every step in words
Show all 10 steps
- original = x = 121. We'll reverse x digit by digit, storing the result in reversed.
- digit = x % 10 = 121 % 10 = 1. Extract the last digit of x.
- reversed = reversed * 10 + digit = 0 * 10 + 1 = 1. Build the reversed number starting with digit 1.
- x = Math.floor(x / 10) = Math.floor(121 / 10) = 12. Remove the last digit from x; x is now 12.
- digit = x % 10 = 12 % 10 = 2. Extract the next last digit.
- reversed = reversed * 10 + digit = 1 * 10 + 2 = 12. Append digit 2; reversed is now 12.
- x = Math.floor(x / 10) = Math.floor(12 / 10) = 1. Remove the last digit; x is now 1.
- digit = x % 10 = 1 % 10 = 1. Extract the final digit.
- reversed = reversed * 10 + digit = 12 * 10 + 1 = 121. Append digit 1; reversed is now 121.
- x = Math.floor(x / 10) = Math.floor(1 / 10) = 0. Loop exits since x = 0. Compare: reversed (121) === original (121). Answer: true.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.