C Online Compiler
Example: Longest Palindrome in Array (String Conversion) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Longest Palindrome in Array (String Conversion) #include <stdio.h> #include <string.h> // For strlen #include <stdlib.h> // For malloc, free #include <limits.h> // For INT_MIN // Function to check if a string is a palindrome // Returns 1 if palindrome, 0 otherwise int isPalindromeString(char *str) { int length = strlen(str); int start = 0; int end = length - 1; // Step 1: Use two pointers to compare characters from both ends while (start < end) { if (str[start] != str[end]) { return 0; // Not a palindrome } start++; end--; } return 1; // It is a palindrome } 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; int maxDigits = -1; int foundPalindrome = 0; // Max digits an int can have (for 32-bit int, ~10 digits + sign + null terminator) // For long long, it could be up to 20 digits. Let's use 15 for safety. char numStr[15]; 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: Convert the number to a string // sprintf returns the number of characters written, which is the length // Handle negative numbers explicitly: negative numbers like -121 would become "-121" // which won't be a palindrome as a string. if (currentNum < 0) { continue; // Skip negative numbers as they are not palindromes by convention } int len = sprintf(numStr, "%d", currentNum); // Step 3: Check if the string representation is a palindrome if (isPalindromeString(numStr)) { foundPalindrome = 1; // Step 4: If it's a palindrome, compare its length with the maximum found so far if (len > maxDigits) { maxDigits = len; longestPalindrome = currentNum; } } } // Step 5: 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