Question
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
Subscribe to see which companies asked this question.
Solution
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
char** fizzBuzz(int n, int* returnSize) {
*returnSize = n;
int i;
char ** str = (char **) malloc(sizeof(char *)*n);
for (i = 0; i < n; i++) {
if ((i+1)%15==0) {
*(str+i) = "FizzBuzz";
} else if ((i+1)%3==0) {
*(str+i) = "Fizz";
} else if ((i+1)%5==0) {
*(str+i) = "Buzz";
} else {
*(str+i) = (char*)malloc(sizeof(char));
sprintf(*(str+i), "%d", i+1);
continue;
}
}
return str;
}