> Interview Breeze

Fizz Buzz

FizzBuzz is a question that every developer should know how to answer. It is commonly used as a first round or warm up question, and will be quickly followed by other, harder questions.

Problem

Write a function that prints the numbers 1 to 100. If the number is a multiple of 3, print fizz instead of the number. If the number is a multiple of 5, print buzz instead of the number. If the number is a multiple of both 3 and 5, print fizzbuzz instead of the number.

Solution

function fizzBuzz() {
    for(var i = 1; i <= 100; i++) {
        var result = ""; // where we will store our string

        if(i % 3 == 0) result += "fizz";
        if(i % 5 == 0) result += "buzz";

        if(result.length > 0) {
            console.log(result);
        } else {
            console.log(i);
        }
    }
}

Using Modulo to find multiples

The crux of this problem is the use of Modulo (the percent sign in the code) to determine whether or not each number i is a multiple of 3 or 5. When you perform a modulo operation, I.E. 10 % 3, it returns the remainder from dividing 10 by 3. In this case, 10 % 3 == 1. Since 10 has a remainder of 1, it is not evenly divisible by 3. Another way to say that, is 10 is not a multiple of 3. In this case, we would not want to print out "fizz".

10 % 5 == 0 though, which means that 10 is a multiple of 5. In this case, we will want to print out buzz, so we add it to the result string.

Printing the result

After we check for the modulo of 3 and 5, we check if the result string has a length. If it was not a multiple of 3 or 5, the string will be empty, and we will instead print i. If it does have a length though, we will print out the result string, which will be either fizz, buzz, or fizzbuzz.


You may also want to read:

Reverse a singly linked list

Given a singly linked list, write a function that returns a linked list with all the nodes in reverse order.

Read More >>
Max Stack

Design a data structure that is similar to a stack. It will only contain unique integers (no integer will ever repeat), and should have a pop, push, peek, and max function that have O(1) time complexity.

Read More >>
Target Subsequence

Given a sequence of positive integers A and an integer T, return whether there is a *continuous sequence* of A that sums up to exactly T.

Read More >>

Python Console