题目描述
给你一个整数 n
,找出从 1
到 n
各个整数的 Fizz Buzz 表示,并用字符串数组 answer
(下标从 1 开始)返回结果,其中:
answer[i] == "FizzBuzz"
如果i
同时是3
和5
的倍数。answer[i] == "Fizz"
如果i
是3
的倍数。answer[i] == "Buzz"
如果i
是5
的倍数。answer[i] == i
(以字符串形式)如果上述条件全不满足。
https://leetcode.cn/problems/fizz-buzz/description/
示例
示例 1:
输入:n = 3
输出:["1","2","Fizz"]
示例 2:
输入:n = 5
输出:["1","2","Fizz","4","Buzz"]
示例 3:
输入:n = 15
输出:["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
解题总结
- 1
在内存中开辟一块连续的空间,每个小空间是一个字符,将这块空间分割成多个小块空间,这就是字符串数组
题目中最长的字符串是"FizzBuzz",该字符串占9个小空间(末尾有个终止符),所以每个小块空间中有9个字符
于是有
char* arr = (char*)malloc(sizeof(char) * 9 * n);
char** answer = (char**)malloc(sizeof(char*) * n);
arr 指针指向开辟的空间,answer 指针对该空间起到一个索引的作用,相当于创建了一个字符串数组
- 2
如果一个数是3和5的倍数,那么这个数也是15的倍数
- 3
将数转换成字符串用到函数 sprintf
C 库函数 int sprintf(char *str, const char *format, …) 发送格式化输出到 str 所指向的字符串。
代码实现
char ** fizzBuzz(int n, int* returnSize){
*returnSize = n;
int i = 0;
char* arr = (char*)malloc(sizeof(char) * 9 * n);
char** answer = (char**)malloc(sizeof(char*) * n);
for (i = 1; i <= n; i++)
{
answer[i - 1] = arr + (i - 1) * 9;
if (i % 15 == 0)
strcpy(answer[i - 1], "FizzBuzz");
else if (i % 3 == 0)
strcpy(answer[i - 1], "Fizz");
else if (i % 5 == 0)
strcpy(answer[i - 1], "Buzz");
else
sprintf(answer[i - 1], "%d", i);
}
*answer = arr;
return answer;
}