Fizz Buzz(412)

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 1:

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

C代码:

char** fizzBuzz(int n, int* returnSize) {
  *returnSize = n;
  char **result = (char**) malloc(sizeof(char*)*n);
  /*  使用else-if 和 mod运算, 比下面的方法时间长一点
  for (int i = 0; i < n;i++) {
    result[i] = (char*) malloc(sizeof(char)*10);
    if ((i+1) % 15 == 0) {
      result[i] =  "FizzBuzz";
    }else if((i+1) % 3 == 0) {
      result[i] =  "Fizz";
    }else if((i+1) % 5 == 0) {
      result[i] =  "Buzz";
    }else{
      sprintf(result[i],"%d",i+1);
    }
  }
  */
  for (int i = 0 ; i < n ; i++) {
    result[i] = (char*)malloc((sizeof(char) *10));
    sprintf(result[i], "%d" , i+1);
  }

  for(int i = 2; i < n; i+= 3) {
    result[i] = "Fizz";
  }
  for(int i = 4; i < n; i+= 5) {
    result[i] = "Buzz";
  }
  for(int i = 14; i < n; i+= 15) {
    result[i] = "FizzBuzz";
  }

  return result;
}

Complexity Analysis:

Time complexity : O(n).
Space complexity : O(1).

思路:

  • 这题思路比较简单.

注意⚠️:

  • C语言 char **问题, 理解为指向字符串数组的首地址的指针就行.
  • C语言 malloc如何使用问题
  • C语言数字转字符串问题.
  • 使用“/” / “%” 运算代价比较高,尽量使用加减.

猜你喜欢

转载自blog.csdn.net/kelly_fumiao/article/details/84985566