The Classic Fizzbuzz Problem
Fizz Buzz is a classic interview question which interviewers ask pretty often. It is a pretty hard problem to solve, but once you figure out the trick to solve the problem, it becomes very easy. It is very important to know how to solve this question because it is designed to help filter out the 99% candidates who can’t seem to program the way out of an interview.
In this blog, I will show one way to solve this FizzBuzz question, but just know there might be various ways to solve this problem, but I will be showing the way I found easier for me.
The Question:
Write a program that console logs the numbers from 1- n, but for multiples of three print
“fizz” instead of the number and for the multiples of five print “buzz”. For numbers which are multiples of both three and five print “fizzbuzz”.
Solution:
To solve this problem, it is important to know how the Modulus operator works. Modulus operator is a way to determine the remainder of a division operation. Instead of returning the result of the division, the modulo operation returns the whole number remainder. The modulus operator, written in most programming languages as %
or mod.
This is pretty much is the line which is the trick to solving FizzBuzz problem.
We will need to iterate from 1 to ≤ n. Then, We will need to use if function to check if the number is multiple of 3 and 5. If it meets the if statement, then we will need to print out “fizzbuzz”. We will do two else if’s to check the next cases which are to check if the number is a multiple of 3 or 5. If the number is a multiple of 3 we will print out “fizz”. If the number is a multiple of 5 we will print out “buzz”. If the number doesn’t meet any of the cases, then we will just print out the number.