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
|
#include <stdio.h>
#define YES ("a palindrome")
#define NO ("NOT a palindrome")
#define CHECK(X) (is_binary_palindrome(X) ? YES : NO)
int is_binary_palindrome(unsigned int n);
unsigned int bin_c (unsigned int a);
unsigned int reverse(unsigned int b);
int main(int argc, char *argv[]) {
const char testStr[] = "Program thinks %u is %s, should be %s\n";
printf ("%d",reverse(98374923874923));
printf (testStr, 0, CHECK(0) , YES);
printf (testStr, 11, CHECK(11), NO);
printf (testStr, 9, CHECK(9), YES);
printf (testStr, 2863289685u, CHECK(2863289685u), YES);
printf (testStr, 268435456, CHECK(268435456), NO);
getch();
return 0;
}
/** Returns 1 iff the binary numeral representing N is a palindrome.
* Ignores leading 0s. */
unsigned int bin_c (unsigned int a){
if (a == 0){
return 0;
}
else{
return (a%2 + 10*bin_c(a/2));
}
}
unsigned int reverse(unsigned int b, int reint){
static int sum = 0;
static int base = 1;
if (reint != 0){
sum = 0;
base = 1;
}
if (b > 0){
reverse(b/10,0);
sum = sum + (b%10)*base;
base = base * 10;
}
return sum;
}
int is_binary_palindrome(unsigned int n) {
unsigned int binary = bin_c(n);
unsigned int reverse_binary = reverse(bin_c(n),1);
if (binary == reverse_binary){
return 1;
}
return 0;
}
|