【题目概要】
412. Fizz Buzz
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"
]
【思路分析】
- 大体上思路比较好分析,针对每一个数都需要判断%3 和 %5,进行分别的处理,注意判断条件的顺序,优先判断是否同时满足
- 需要注意的是每一列的字符串长度不会大于10
- 字符串赋值用strcpy函数,数字转字符串用sprintf函数
- 如果用下标赋值的方式,需要在结束处加上‘\0’
【示例代码】
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** fizzBuzz(int n, int* returnSize)
{
char **re = (char**)malloc(sizeof(char*)*(n+1));
for(int num=1; num<=n; num++)
{
int row = num-1;
re[row] = (char*)malloc(sizeof(char)*32);
if(num%3 == 0 && num%5 == 0)
{
strcpy(re[row], "FizzBuzz");
}
else if(num%3 == 0)
{
strcpy(re[row], "Fizz");
}
else if(num%5 == 0)
{
strcpy(re[num-1], "Buzz");
}
else
{
char numstr[20] = {0};
sprintf(numstr, "%d", num);
strcpy(re[row], numstr);
}
// printf("%s", re[row]);
}
*returnSize = n;
return re;
}