From e383ef2260ef4d5ba0a4acb9f7d0e0ea1b129aa0 Mon Sep 17 00:00:00 2001 From: kevin Date: Sat, 9 Feb 2019 17:44:05 -0500 Subject: [PATCH] Add C solution for problem 32 --- problem-32.c | 124 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 problem-32.c diff --git a/problem-32.c b/problem-32.c new file mode 100644 index 0000000..fdddc75 --- /dev/null +++ b/problem-32.c @@ -0,0 +1,124 @@ +#include +#include + +#define MAX_NUM 9999 + +typedef struct Node { + int data; + struct Node* next; +} Node; + + +Node* create(int data, Node* node) +{ + Node* new = (Node*)malloc(sizeof(Node)); + if (new == NULL) { + printf("Error allocating memory\n"); + exit(1); + } + + new->data = data; + new->next = node; + return new; +} + + +Node* prepend(Node* head, int data) +{ + return create(data, head); +} + + +int contains(Node* head, int data) +{ + Node* cursor = head; + + while (cursor != NULL) { + if (cursor->data == data) + return 1; + cursor = cursor->next; + } + + return 0; +} + + +int sum(Node* head) +{ + int total = 0; + Node* cursor = head; + + while (cursor != NULL) { + total += cursor->data; + cursor = cursor->next; + } + + return total; +} + + +int countDigits(long num) +{ + int count = 0; + + while (num != 0) { + count++; + num /= 10; + } + + return count; +} + + +int isNineDigits(int i, int j) +{ + return 9 == countDigits(i) + countDigits(j) + countDigits(i*j); +} + + +int isNinePandigital(int i, int j) +{ + int rem; + int digits = 0; + int prod = i*j; + + if (!(isNineDigits(i, j))) + return 0; + + while (i>0) { + rem = i % 10; + digits ^= 1 << rem; + i /= 10; + } + + while (j>0) { + rem = j % 10; + digits ^= 1 << rem; + j /= 10; + } + + while (prod>0) { + rem = prod % 10; + digits ^= 1 << rem; + prod /= 10; + } + + return digits == 1022; /* 1022 == 1111111110 in binary */ +} + + +int main(int argc, char** argv) +{ + int i, j; + int sumProds; + Node* pandigitals = NULL; + + for (i=1; i