-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfizzbuzz.c
51 lines (47 loc) · 1.11 KB
/
fizzbuzz.c
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
struct Map {
int key;
char* value;
};
char* itoa(int number) {
int n = log10(number) + 1;
int i;
char *numberArray = malloc(sizeof *numberArray * n);
for (i = n-1; i >= 0; --i, number /= 10)
{
numberArray[i] = (number % 10) + '0';
}
return numberArray;
}
char* concat(char* arr1, char* arr2) {
int newSize = strlen(arr1) + strlen(arr2) + 1;
char* newArr = malloc(sizeof *newArr * newSize);
strcpy(newArr,arr1);
strcat(newArr,arr2);
return newArr;
}
int main()
{
struct Map dict[2] = {
{3, "Fizz"},
{5, "Buzz"}
};
char* output;
for (int i = 1; i <= 100; i++) {
output = "";
for ( int j = 0; j < sizeof dict / sizeof dict[0]; j++ ) {
if (i % dict[j].key == 0) {
output = concat(output, dict[j].value);
}
}
if (output == "") {
output = itoa(i);
}
printf("%s\n", output);
free(output);
}
return 0;
}