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”
]
注意:
1、char**的使用,每一个数组都需要创建空间;
2、returnsize需要赋值后再返回;
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
char** fizzBuzz(int n, int* returnSize) {
if (n <= 0)
{
*returnSize = 0;
return NULL;
}
char** arr = (char**)malloc(sizeof(char*)*n);
for (int i = 0; i < n; i++)
{
int temp = i + 1;
int m = temp%3, s = temp%5;
if (m == 0 && s != 0)
{
arr[i] = (char*)malloc(5 * sizeof(char));
strcpy(arr[i], "Fizz");
}
else if (s == 0 && m != 0)
{
arr[i] = (char*)malloc(5 * sizeof(char));
strcpy(arr[i], "Buzz");
}
else if (s == 0 && m == 0)
{
arr[i] = (char*)malloc(9 * sizeof(char));
strcpy(arr[i], "FizzBuzz");
}
else
{
char buf[32] = { 0 };
sprintf(buf, "%d", temp);
arr[i] = (char*)malloc((strlen(buf) + 1) * sizeof(char));
strcpy(arr[i], buf);
}
}
*returnSize = n;
return arr;
}