DSA Tracker

Visualize

Palindrome Number

time O(n)space O(1)

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

121
[0]

original = x = 121. We'll reverse x digit by digit, storing the result in reversed.

  • x=0· arr[0] = 121
Pseudocode
1FUNCTION isPalindrome(x):
2 IF x < 0: RETURN false
3 original = x
4 reversed = 0
5 WHILE x > 0:
6 digit = last digit of x (x mod 10)
7 reversed = reversed * 10 + digit
8 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
  1. original = x = 121. We'll reverse x digit by digit, storing the result in reversed.
  2. digit = x % 10 = 121 % 10 = 1. Extract the last digit of x.
  3. reversed = reversed * 10 + digit = 0 * 10 + 1 = 1. Build the reversed number starting with digit 1.
  4. x = Math.floor(x / 10) = Math.floor(121 / 10) = 12. Remove the last digit from x; x is now 12.
  5. digit = x % 10 = 12 % 10 = 2. Extract the next last digit.
  6. reversed = reversed * 10 + digit = 1 * 10 + 2 = 12. Append digit 2; reversed is now 12.
  7. x = Math.floor(x / 10) = Math.floor(12 / 10) = 1. Remove the last digit; x is now 1.
  8. digit = x % 10 = 1 % 10 = 1. Extract the final digit.
  9. reversed = reversed * 10 + digit = 12 * 10 + 1 = 121. Append digit 1; reversed is now 121.
  10. 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.