C Online Compiler
Example: Longest Palindrome in Array (Iterative Digit Reversal) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Longest Palindrome in Array (Iterative Digit Reversal) #include <stdio.h> #include <limits.h> // For INT_MIN // Function to check if a number is a palindrome // Returns 1 if palindrome, 0 otherwise int isPalindrome(int num) { // Negative numbers are not typically considered palindromes // Single digit numbers (0-9) are palindromes if (num < 0) { return 0; } if (num >= 0 && num <= 9) { return 1; } int originalNum = num; int reversedNum = 0; // Step 1: Reverse the number while (num > 0) { int digit = num % 10; reversedNum = reversedNum * 10 + digit; num /= 10; } // Step 2: Compare the original number with the reversed number return originalNum == reversedNum; } // Function to count the number of digits in an integer int countDigits(int num) { if (num == 0) { return 1; } int count = 0; // Handle negative numbers by converting to positive for digit counting if (num < 0) { num = -num; } while (num > 0) { num /= 10; count++; } return count; } int main() { int numbers[] = {121, 23, 4554, 9, 78987, 1001, 5, 987654321, 0, -121}; int n = sizeof(numbers) / sizeof(numbers[0]); int longestPalindrome = INT_MIN; // Initialize with a value indicating no palindrome found int maxDigits = -1; int foundPalindrome = 0; printf("Array elements: "); for (int i = 0; i < n; i++) { printf("%d ", numbers[i]); } printf("\n\n"); // Step 1: Iterate through each number in the array for (int i = 0; i < n; i++) { int currentNum = numbers[i]; // Step 2: Check if the current number is a palindrome if (isPalindrome(currentNum)) { foundPalindrome = 1; int currentDigits = countDigits(currentNum); // Step 3: If it's a palindrome, compare its digit count with the maximum found so far if (currentDigits > maxDigits) { maxDigits = currentDigits; longestPalindrome = currentNum; } } } // Step 4: Print the result if (foundPalindrome) { printf("The longest palindrome in the array is: %d\n", longestPalindrome); printf("It has %d digits.\n", maxDigits); } else { printf("No palindromes found in the array.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS