Menu Close

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

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

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

References:

https://www.cplusplus.com/

Posted in C++, golang program, Leetcode

Leave a Reply

Your email address will not be published. Required fields are marked *