FizzBuzz is one the most common questions asked in interviews, let's take a look at how you can solve it efficiently and ace the interview.
First we must understand what fizzbuzz is.
Here is how this game goes, you have to count numbers from 1-100. When you encounter a multiple of 3, you have to say "fizz" and when you encounter a multiple of 5 , you have to say "buzz"
Here is how this game goes, you have to count numbers from 1-100. When you encounter a multiple of 3, you have to say "fizz" and when you encounter a multiple of 5 , you have to say "buzz"
and when you encounter a multiple of 3 and 5 you have to say "fizzbuzz".
Does that seem confusing?
Let's take a look a practical example, Tom and Jeff are playing Fizzbuzz
Does that seem confusing?
Let's take a look a practical example, Tom and Jeff are playing Fizzbuzz
Here's what it would look like
1 - Tom : 1
2 - Jeff : 2
3 - Tom : Fizz
4 - Jeff : 4
5 - Tom : Buzz
6 - Tom : Fizz
7 - Jeff : 7
8 - Tom : 8
9 - Jeff : Fizz
10 - Tom : Buzz
11 - Tom : 11
12 - Jeff : Fizz
13 - Tom : 13
14 - Jeff : 14
15 - Tom : FizzBuzz
...
100 - Jeff : Buzz
1 - Tom : 1
2 - Jeff : 2
3 - Tom : Fizz
4 - Jeff : 4
5 - Tom : Buzz
6 - Tom : Fizz
7 - Jeff : 7
8 - Tom : 8
9 - Jeff : Fizz
10 - Tom : Buzz
11 - Tom : 11
12 - Jeff : Fizz
13 - Tom : 13
14 - Jeff : 14
15 - Tom : FizzBuzz
...
100 - Jeff : Buzz
Well, this is poor and inefficient way of solving this problem.
Why?
Let's say the interview now asks you to print fizz for multiples of 7 and fizzbuzz for multiples of 7 and 5.
You have to change the numbers in all the if-else statements, YUCK!
Why?
Let's say the interview now asks you to print fizz for multiples of 7 and fizzbuzz for multiples of 7 and 5.
You have to change the numbers in all the if-else statements, YUCK!
Now if you are asked to print fizz for ever multiple of 7 you just have to change one line of code! you can even add more numbers like if you want bark for every multiple of 7 along with fizz for 3 and buzz for 5, you can easily do it! Not to mention it is more readable!
Yay!
Yay!
Now here's a challenge for you, try doing this in JavaScript.
If you have an even more efficient way of solving this problem, let me know in the replies
If you have an even more efficient way of solving this problem, let me know in the replies