# Leetcode 412- Fizz Buzz solution

Here, this tutorial will help you to understand about Fizz Buzz solution of leetcode 412 problem with algorithm.

You are given an integer value lets say `n`. You have to returnÂ a string arrayÂ `result` where:

• `result[i] == "FizzBuzz"`Â ifÂ `i`Â is divisible byÂ `3`Â andÂ `5`.
• `result[i] == "Fizz"`Â ifÂ `i`Â is divisible byÂ `3`.
• `result[i `== “Buzz”Â ifÂ `i`Â is divisible byÂ `5`.
• `result[i] == i`Â (as a string) if none of the above conditions are true.

### Example 1:

```Input:
num = 4
result = ["1", "2", "Fizz", "4"]

num = 5
result = ["1","2","Fizz","4","Buzz"]```

## Algorithm for Fizz Buzz problem:

• Iterate over number from 1 to n
• For each number, If It is divisible by 3 and 5 then store “`FizzBuzz`” to string array.
• For each number, If It is divisible by 3 then store “`Fizz`” to string array.
• For each number, If It is divisible by 5 then store “`Buzz`” to string array.
• Store number as string in array If none of the above condition is true.

## Fizz Buzz solution code in Go

```package main

import (
"fmt"
"strconv"
)

func fizzBuzz(n int) []string {
str := []string{}

for i := 1; i <= n; i++ {
if i % 3 == 0 && i % 5 == 0 {
str = append(str, "FizzBuzz")
} else if i % 3 == 0 {
str = append(str, "Fizz")
} else if i % 5 == 0 {
str = append(str, "Buzz")
} else {
str = append(str, strconv.Itoa(i))
}
}
return str
}

func main() {
str := fizzBuzz(4)

for _, val := range(str) {
fmt.Println(val)
}
}
```

## Fizz Buzz problem code in C++

```#include <iostream>
#include <vector>

using namespace std;

vector<string> fizzBuzz(int n) {
vector<string> v;

for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
v.push_back("FizzBuzz");
} else if (i % 3 == 0) {
v.push_back("Fizz");
} else if (i % 5 == 0) {
v.push_back("Buzz");
} else {
v.push_back(to_string(i));
}
}
return v;
}

int main() {
vector<string> v = fizzBuzz(4);

for(auto it : v) {
cout<<it<<" ";
}
}
```

https://www.techieindoor.com/category/golang/

References:

https://www.cplusplus.com/

Posted in C++, golang program, Leetcode