当前位置: 首页> 汽车> 新车 > 软件项目管理案例_企业管理培训课程多少钱_seo教学培训_怎么做网站?

软件项目管理案例_企业管理培训课程多少钱_seo教学培训_怎么做网站?

时间:2025/7/11 22:53:32来源:https://blog.csdn.net/navicheung/article/details/142933501 浏览次数: 0次
软件项目管理案例_企业管理培训课程多少钱_seo教学培训_怎么做网站?

412. Fizz Buzz

Given an integer n, return a string array answer (1-indexed) where:

  • answer[i] == “FizzBuzz” if i is divisible by 3 and 5.
  • answer[i] == “Fizz” if i is divisible by 3.
  • answer[i] == “Buzz” if i is divisible by 5.
  • answer[i] == i (as a string) if none of the above conditions are true.
     
Example 1:

Input: n = 3
Output: [“1”,“2”,“Fizz”]

Example 2:

Input: n = 5
Output: [“1”,“2”,“Fizz”,“4”,“Buzz”]

Example 3:

Input: n = 15
Output:
[“1”,“2”,“Fizz”,“4”,“Buzz”,“Fizz”,“7”,“8”,“Fizz”,“Buzz”,“11”,“Fizz”,“13”,“14”,“FizzBuzz”]

Constraints:
  • 1 < = n < = 1 0 4 1 <= n <= 10^4 1<=n<=104

From: LeetCode
Link: 412. Fizz Buzz


Solution:

Ideas:

1. Memory Allocation:

  • The function returns an array of strings, so we first allocate memory for the array result that will hold the strings.
  • Each string requires memory allocation separately. Since the maximum string length is 8 characters (for “FizzBuzz”) plus 1 for the null terminator (\0), we allocate space for each string using malloc(9 * sizeof(char)).

2. FizzBuzz Logic:

  • For each number from 1 to n, we check:
    • If the number is divisible by both 3 and 5, we assign “FizzBuzz”.
    • If it’s divisible by only 3, we assign “Fizz”.
    • If it’s divisible by only 5, we assign “Buzz”.
    • Otherwise, we convert the number to a string using snprintf and store it in the array.

3. Returning the Result:

  • The function returns the result array, and the size of the array (n) is returned through the returnSize pointer.
  • The main function demonstrates how to call this function and free the allocated memory properly.
Code:
/*** Note: The returned array must be malloced, assume caller calls free().*/
char** fizzBuzz(int n, int* returnSize) {*returnSize = n;char** result = (char**)malloc(n * sizeof(char*)); // Allocate memory for the result arrayfor (int i = 1; i <= n; i++) {result[i - 1] = (char*)malloc(9 * sizeof(char)); // Allocate memory for each string (maximum length is 8 for "FizzBuzz" + 1 for '\0')if (i % 3 == 0 && i % 5 == 0) {strcpy(result[i - 1], "FizzBuzz");} else if (i % 3 == 0) {strcpy(result[i - 1], "Fizz");} else if (i % 5 == 0) {strcpy(result[i - 1], "Buzz");} else {snprintf(result[i - 1], 9, "%d", i); // Convert the integer to a string}}return result;
}
关键字:软件项目管理案例_企业管理培训课程多少钱_seo教学培训_怎么做网站?

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: