---
# System prepended metadata

title: Leetcode 1071. Greatest Common Divisor of Strings
tags: [leetcode]

---

---
title: Leetcode 412. Fizz Buzz
tags: leetcode
---

# Leetcode 412. Fizz Buzz

## 題目連結

https://leetcode.com/problems/fizz-buzz/description/

## 題目敘述

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**

:::success
Input: n = 3
Output: ["1","2","Fizz"]
:::

**Example 2**

:::success
Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]
::: 

**Example 3**

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

**Constraints**

`1 <= n <= 104`

---

## 解題思路

題目要回傳一個長度為n，entry為字串"1"到字串"n-1"的array，只是碰到3, 5 或 15 的倍數時需存放對應字串，因此，我透過`for loop`，從1開始跑到n，判斷是否是上述的倍數，若是，存入對應字串，若否，則存入該數字的字串。

**c++程式碼**

```cpp=
class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> answer;
        for(int i = 1 ; i <= n ; i++) {
            if(i % 15 == 0)
                answer.push_back("FizzBuzz");
            else if(i % 3 == 0)
                answer.push_back("Fizz");
            else if(i % 5 == 0)
                answer.push_back("Buzz");
            else
                answer.push_back(to_string(i));
        }
        return answer;
    }
};
```

**執行結果**

![](https://hackmd.io/_uploads/SkREPnnb6.png)

## Solution 其他解法

先將每個數字字串存入vector，在額外將每個3, 5, 15 的倍數對應的位置更改為對應字串，目的可能是減少做 % 運算所花費的時間。

```cpp=
class Solution {
public:
    vector<string> fizzBuzz(int n) {
       vector<string> answer(n);
        for(int i = 0 ; i < n ; i++) {
            answer[i] = to_string(i+1);
        }
        for(int i = 2 ; i < n ; i += 3) {
            answer[i] = "Fizz";
        }
        for(int i = 4 ; i < n ; i += 5) {
            answer[i] = "Buzz";
        }
        for(int i = 14 ; i < n ; i += 15) {
            answer[i] = "FizzBuzz";
        }
        return answer;
    }
};
```