1. 程式人生 > >Fizz Buzz(412)

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語言數字轉字串問題.
  • 使用“/” / “%” 運算代價比較高,儘量使用加減.