Palindrome
Number theory
Programming
Algorithms
Coding tasks

How do I check if a number is a palindrome?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Overview

A palindrome is a number (or text) that reads the same forward and backward. Checking if a number is a palindrome is a common problem encountered in computer science and mathematics. This article provides a detailed guide on various approaches to determine if a number is a palindrome, complete with technical explanations and examples.

Palindrome Checking Approaches

1. String Reversal Method

The most straightforward approach to check if a number is a palindrome is by converting it to a string, reversing the string, and comparing it to the original string.

Steps:

  1. Convert the number to a string.
  2. Reverse the string.
  3. Compare the reversed string with the original string.

Example:

python
1def is_palindrome(num):
2    str_num = str(num)
3    reversed_str_num = str_num[::-1]
4    return str_num == reversed_str_num
5
6# Test the function
7print(is_palindrome(121))  # Output: True
8print(is_palindrome(-121)) # Output: False

2. Numerical Reversal Method

This method involves reversing the digits of the number itself without converting it to a string. It's often used to avoid extra space usage or where string operations are not preferred.

Steps:

  1. Initialize a variable to store the reversed number.
  2. Extract digits from the number in reverse order.
  3. Build the reversed number.
  4. Compare the original number with the reversed number.

Mathematical Insights:

  • Extract each digit using modulo and integer division.
  • Shift digits in the reversed number using multiplication and addition.

Example:

python
1def is_palindrome(num):
2    if num < 0:  # Negative numbers are not palindromes
3        return False
4        
5    original_num = num
6    reversed_num = 0
7    
8    while num != 0:
9        digit = num % 10
10        reversed_num = reversed_num * 10 + digit
11        num //= 10
12        
13    return original_num == reversed_num
14
15# Test the function
16print(is_palindrome(121))  # Output: True
17print(is_palindrome(-121)) # Output: False

3. Half Reversal Method

Instead of reversing the entire number, the half-reversal method involves reversing only the second half of the digits. This method is more efficient for large numbers.

Steps:

  1. Reverse only the second half of the number's digits.
  2. Compare the reversed half with the first half.

Example:

python
1def is_palindrome(num):
2    if num < 0 or (num != 0 and num % 10 == 0):
3        return False
4        
5    reversed_half = 0
6
7    while num > reversed_half:
8        digit = num % 10
9        reversed_half = reversed_half * 10 + digit
10        num //= 10
11        
12    return num == reversed_half or num == reversed_half // 10
13
14# Test the function
15print(is_palindrome(121))  # Output: True
16print(is_palindrome(10))   # Output: False

Key Points Summary

Below is a table summarizing the key characteristics of the palindrome checking methods:

MethodApproachSpace ComplexityTime Complexity
String ReversalConvert to string & reverseO(n)O(n)O(n)O(n)
Numerical ReversalReverse using digits & compareO(1)O(1)O(n)O(n)
Half ReversalReverse half & compareO(1)O(1)O(log10(n))O(\log_{10}(n))

Additional Details

Palindromes in Different Bases

A number's palindromic property can change depending on the base. For instance, 121 in base 10 is a palindrome, but it is not in base 2 (binary). Typically, a generalized approach might involve converting the number into the appropriate base and checking for palindrome properties accordingly.

Applications of Palindromes

  • Computer Science: String algorithms use palindrome properties in problems like longest palindromic substring, palindrome partitioning, etc.
  • Cryptography: Certain encryption schemes may employ palindromes due to their reversible nature.
  • Mathematics: Palindromic numbers are part of sequences and patterns that bear significance in number theory.

In summary, checking if a number is a palindrome can be achieved through various methods, each suitable for different scenarios. Understanding these methods provides fundamental insight into number theory and algorithm design.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.