1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
/* Main Function*/
int main()
{
bool checkNumPalindrome( long long int num );
bool checkStringPalindrome (char *s);
void decToBinary( char *bin, int num, int *digits);
long long int limit, num, sum;
bool check1, check2;
char bin[100] = {};
int digits = 0;
printf("This Program checks for numbers within the limit you entered for Double"
"base Palindromes in decimal base (10) and binary base (2).\n");
printf("\nPlease enter the limit: ");
scanf("%lld", &limit);
num = 1;
sum = 0;
while(num <= limit)
{
check1 = checkNumPalindrome(num);
if( check1 == true)
{
decToBinary(bin, num, &digits);
check2 = checkStringPalindrome(bin);
if(check2 == true)
{
printf("\n%lld is a Double base palindrome.\n", num);
printf("In Decimal (base 10) : %lld\n", num);
printf("In Binary (base 2) : ");
int i;
for(i = 0; i < digits; i++)
{
printf("%d", bin[i]);
}
sum = sum + num;
printf("\n");
}
*bin = 0;
}
num++;
}
printf("\nThe total sum is %lld.\n", sum);
return 0;
}
/*Function to check if a number is Palindrome*/
bool checkNumPalindrome( long long int num )
{
long long int originalNum, reverseNum;
int remainder;
originalNum = num;
reverseNum = 0;
while( num > 0 )
{
remainder = num % 10;
reverseNum = reverseNum*10 + remainder;
num/=10;
}
if(originalNum == reverseNum)
return true;
else
return false;
}
/*Function to check if an array is a palindrome*/
bool checkStringPalindrome (char *bin)
{
int a,b;
for (a = 0, b = strlen(bin)-1 ; a < b ; a++, b--)
{
if (bin[a] != bin[b])
return false; // Not palindrome
}
return true; //Palindrome
}
/*Function to convert a number from decimal base to binary using recursion*/
void decToBinary( char *bin, int num, int *digits)
{
int i, j, k;
i = 0;
int count = 0;
while(num > 0)
{
bin[i] = num%2;
num = num/2;
i++;
count++;
}
*digits = count;
}
|