How to Check if a Number is a Palindrome in C

Understanding Palindromes in Programming

A palindrome is a number (or word) that reads the same backward as forward. For example, 121, 1331, and 12321 are all palindromic numbers. In this article, I'll explain how to implement an efficient isPalindrome() function in C that checks whether an integer is a palindrome.

Complete C Implementation with Explanation

Here's a robust implementation of the palindrome checker function with detailed comments:

#include <stdio.h>
#include <stdbool.h> // For using bool type (C99 and later)

/**
 * Checks if an integer is a palindrome
 * @param num The number to check
 * @return true if the number is a palindrome, false otherwise
 */
bool isPalindrome(int num) {
    // Handle negative numbers (they can't be palindromes)
    if (num < 0) {
        return false;
    }
    
    // Special case: numbers ending with 0 (except 0 itself)
    if (num % 10 == 0 && num != 0) {
        return false;
    }
    
    int originalNum = num; // Store the original number
    long reversed = 0;     // Using long to prevent integer overflow
    
    // Reverse the number digit by digit
    while (num > 0) {
        int digit = num % 10;          // Extract the last digit
        reversed = reversed * 10 + digit; // Build the reversed number
        num /= 10;                     // Remove the last digit
    }
    
    // Compare the original number with the reversed one
    return originalNum == reversed;
}

int main() {
    // Test cases
    int testNumbers[] = {121, 123, 12321, -121, 10, 0, 123454321};
    int count = sizeof(testNumbers) / sizeof(testNumbers[0]);
    
    for (int i = 0; i < count; i++) {
        int num = testNumbers[i];
        if (isPalindrome(num)) {
            printf("%d is a palindrome.\n", num);
        } else {
            printf("%d is not a palindrome.\n", num);
        }
    }
    
    return 0;
}

How the Palindrome Checker Works

Let's break down the implementation step by step:

  1. Negative Numbers Check:
    • Negative numbers can't be palindromes because of the negative sign (e.g., -121 reversed is 121-).
    • We immediately return false for any negative input.
  2. Numbers Ending with Zero:
    • Any number ending with 0 (except 0 itself) can't be a palindrome because numbers don't start with 0.
    • For example, 10 reversed would be 01, which isn't the same as 10.
  3. Reversing the Number:
    • We initialize reversed to 0 and then process each digit:
      • num % 10 gives us the last digit (e.g., 123 % 10 = 3)
      • We add this digit to reversed (which gets multiplied by 10 to shift digits left)
      • We remove the last digit from num using integer division by 10
  4. Comparison:
    • After reversing, we simply compare the original number with the reversed version.

Example Walkthrough

Let's see how this works with the number 12321:

  1. Original number: 12321
  2. First iteration:
    • digit = 12321 % 10 = 1
    • reversed = 0 * 10 + 1 = 1
    • num = 12321 / 10 = 1232
  3. Second iteration:
    • digit = 1232 % 10 = 2
    • reversed = 1 * 10 + 2 = 12
    • num = 1232 / 10 = 123
  4. Third iteration:
    • digit = 123 % 10 = 3
    • reversed = 12 * 10 + 3 = 123
    • num = 123 / 10 = 12
  5. Fourth iteration:
    • digit = 12 % 10 = 2
    • reversed = 123 * 10 + 2 = 1232
    • num = 12 / 10 = 1
  6. Fifth iteration:
    • digit = 1 % 10 = 1
    • reversed = 1232 * 10 + 1 = 12321
    • num = 1 / 10 = 0 (loop ends)

Finally, we compare originalNum (12321) with reversed (12321) and return true.

Handling Edge Cases

Our improved implementation handles several edge cases:

  • Negative numbers: Correctly identifies they're not palindromes
  • Numbers ending with 0: Properly handles these special cases
  • Single-digit numbers: All single-digit numbers (0-9) are palindromes
  • Large numbers: Uses long for reversal to prevent integer overflow

Optimized Approach (Half Number Reversal)

For very large numbers, we can optimize by only reversing half of the number:

bool isPalindromeOptimized(int num) {
    if (num < 0 || (num % 10 == 0 && num != 0)) {
        return false;
    }
    
    int reversedHalf = 0;
    
    // When original number becomes less than reversed half,
    // we've processed half the digits
    while (num > reversedHalf) {
        reversedHalf = reversedHalf * 10 + num % 10;
        num /= 10;
    }
    
    // For even digits: num == reversedHalf
    // For odd digits: num == reversedHalf / 10 (middle digit doesn't matter)
    return num == reversedHalf || num == reversedHalf / 10;
}

This approach is more efficient as it only processes half the digits while still accurately determining if the number is a palindrome.

Conclusion

Checking for palindromic numbers in C is a great exercise in understanding number manipulation and algorithmic thinking. The implementation we've discussed handles all edge cases and provides both a straightforward and an optimized solution. You can use this function in various applications like:

  • Validating user input
  • Solving programming puzzles
  • Algorithmic challenges
  • Number theory applications

Remember that understanding how the code works is more important than just copying it. Try modifying the function to handle different data types or to work with strings as well!