Visualize

Pattern visualizer

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. Animated on: Given an integer x, determine if it's a palindrome by reversing its digits using mod and divide (no string conversion)..

Math

time O(n)space O(1)step 1 / 10
121
[0]
line 3

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

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

Where to practice Math