DEV Community

loading...

Leetcode: FizzBuzz

greedybrain profile image Naya Willis ・2 min read

Today, I will be solving the famous FizzBuzz code challenge on Leetcode. The instructions are as follows.

Instructions

For numbers with 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”. The twist is, they want you to return the string representation of each output stored in an array.

Overview

const fizzBuzz = n => {
    // Code goes here
};
Enter fullscreen mode Exit fullscreen mode

Let's play

Step 1:

I created 2 variables. One to handle a counter in a while loop, and one to store fizz buzz values as strings.

let count = 1 //Starting at 1 because we only want to check from number 1 to n

let results = []
Enter fullscreen mode Exit fullscreen mode

Step 2:

Start the while loop

while(count <= n) {
        if(count % 3 === 0 && count % 5 === 0) {
            results.push("FizzBuzz")
        } else if(count % 3 === 0) {
            results.push("Fizz")
        } else if(count % 5 === 0) {
            results.push("Buzz")
        } else {
            results.push(count.toString())
        }
        count++
}
Enter fullscreen mode Exit fullscreen mode

In this while loop a few things are happening. We set a condition in the while loop to do what ever it is in the while loop block as long as the current count is less than n (n = any number).

Then we setup our if else block. The first one is checking to see if count divided by both 3 and 5 is equal to 0. We should do this first to avoid having only Fizz or only Buzz print out when it see's that a count is divisible by ONLY that number. So remember, it should be FizzBuzz when count is divisible by both 3 and 5. If it is we push the string "FizzBuzz" into the results array.

In the else if's we are checking if count is divisible only by 3, and then only by 5. In that case either "Fizz" or "Buzz" will be appended to the array.

In the event that count isn't divisible by either 3 or 5 we'll stringify the current count and then append it to the array. For example => 1. 1 is not divisible by 3 or 5 so we'll just push 1 as a string ( "1" ).

Finally we return the results array. So after all is good we have...

const fizzBuzz = n => {
    let count = 1
    let results = []
    while(count <= n) {
        if(count % 3 === 0 && count % 5 === 0) {
            results.push("FizzBuzz")
        } else if(count % 3 === 0) {
            results.push("Fizz")
        } else if(count % 5 === 0) {
            results.push("Buzz")
        } else {
            results.push(count.toString())
        }
        count++
    }
    return results
};
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

pic
Editor guide
Collapse
bias profile image
Tobias Nickel

do you know the enterprise implementation?

it is very impressive