Algorithmspalindrome check number

Palindrome Check on Numbers (Digits Forward and Back)

TT
Testlaa Team
May 14, 20261 min read

Palindrome checks on numbers usually mean: does the digit sequence read the same forwards and backwards? The string trick s == s[::-1] is clear; the math trick reverses half the digits to avoid building a long string for huge integers.

Why this shows up in the real world

CAPTCHA or PIN policies sometimes forbid trivial symmetric codes. Odometer puzzles ask which next mileage is palindromic.

Core idea (explained for students)

Convert with s = str(abs(n)) (handle sign explicitly if required). For overflow-safe numeric reversal, peel digits with % 10 and // 10 until halfway, then compare.

Try this in Python

def is_digit_palindrome(n: int) -> bool:
    s = str(abs(n))
    return s == s[::-1]


print(is_digit_palindrome(121), is_digit_palindrome(123))

Common mistakes

  • Leading zeros disappear when you stringify an integer—preserve them if the problem treats the value as a digit string.
  • Negative numbers: decide whether -121 should count as palindrome.

Key takeaways

  • Pick string vs numeric reversal based on constraints (size, leading zeros).
  • Odd-length palindromes: middle digit can be ignored in half-reversal logic.

Tags:

StringsPythonStudents