Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
All palindrome numbers in a list?
Here we will see one simple problem. We have to find all numbers that are palindrome in nature in a given list. The approach is simple, take each number from list and check it is palindrome or not, and print the number.
Syntax
bool isPalindrome(int n); void getAllPalindrome(int arr[], int n);
Algorithm
getAllPalindrome(arr, n)
Begin
for each element e in arr, do
if e is palindrome, then
print e
end if
done
End
Example
This program checks each number in the array to determine if it reads the same forwards and backwards −
#include <stdio.h>
#include <stdbool.h>
bool isPalindrome(int n) {
int reverse = 0, t;
t = n;
while (t != 0) {
reverse = reverse * 10;
reverse = reverse + t % 10;
t = t / 10;
}
return (n == reverse);
}
void getAllPalindrome(int arr[], int n) {
for (int i = 0; i < n; i++) {
if (isPalindrome(arr[i])) {
printf("%d ", arr[i]);
}
}
}
int main() {
int arr[] = {25, 145, 85, 121, 632, 111, 858, 45};
int n = sizeof(arr) / sizeof(arr[0]);
printf("All palindromes: ");
getAllPalindrome(arr, n);
printf("
");
return 0;
}
All palindromes: 121 111 858
How It Works
- The
isPalindrome()function reverses the number digit by digit using modulo and division operations. - It compares the original number with its reverse to determine if it's a palindrome.
- The
getAllPalindrome()function iterates through the array and prints only palindromic numbers.
Conclusion
This approach efficiently finds all palindrome numbers by reversing each number and comparing it with the original. The time complexity is O(n × d) where n is array size and d is average digits per number.
Advertisements
