TheRightLane on Coding

Fizzbuzz In 2 minutes

September 12, 2017

If you are going to get a coding job you are going to have to interview. At one of those interviews, eventually, you will get asked to do fizzbuzz.

So, what is it?

Fizzbuzz is a simple question

There is a child's counting game called Fizzbuzz, it goes like this.
1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz...
If the number is a multiple of 3 say fizz.
if it is a multiple of 5 say buzz.
if it is a multiple of both 3 and 5 (think 15) then it is fizzbuzz!
You write a function that plays fizzbuzz from 1 to 100

Why does anyone care?

This test is used to weed out candidates who don't have the minimum math and logical skills to be professional coders.

What's the answer?

In Swift

for i in 1..<101 {
    if i % 3 == 0 && i % 5 == 0 {
        print ("fizzbuzz")
    }
    else if i % 3 == 0 {
        print ("fizz")
    }
    else if i % 5 == 0 {
        print ("buzz")
    }
    else {
        print (i)
    }
}

That code would be better if...

It's a basic example.
A temporary string variable would be better.
Using map would be better. But it's supposed to be basic

What about in other languages?

You do it!

Details please?

Can do!

The first part is kind of a trick. We play the game starting at 1 not 0. Since most people start loops at zero this is an easy trap.

Need more info on Swift loops click here

for i in 1..<101 {

The modulo is the second place people get tripped up. Lots of coders have never used modulus before.
It's also easy to forget to put fizzbuzz first.

    if i % 3 == 0 && i % 5 == 0 {
        print ("fizzbuzz")
    }

Don't forget the elses!

    else if i % 3 == 0 {
        print ("fizz")
    }
    else if i % 5 == 0 {
        print ("buzz")
    }

Sooooo many people forget this part. You have to print the number if it isn't fizz, buzz or fizzbuzz

    else {
        print (i)
    }
}

Takeaways

Fizzbuzz isn't hard. But it is all about the details. If you are asked this or any questions like it. Make sure you are picking up on all the little details that he interviewer is using to trip you up!

Knock 'em dead!

Lane Thompson