Techieindoor

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:

Example 1:

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

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

Algorithm for Fizz Buzz problem:

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<<" ";
    }
}

To learn more about C++ pls refer given below link:

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

C++ –

References:

https://www.cplusplus.com/

Exit mobile version