In this LeetCode problem, we’re given what is arguably the best known programming challenge out there: FizzBuzz. For those few of you who have never heard of such a thing, the idea is to create a function that will count from 1 to N (N being a number provided to the function), outputting the number as it goes. However, if it encounters a multiple of 3, it will output “Fizz”, if it outputs a multiple of 5, it will output “Buzz”, and if it encounters a multiple of both 3 and 5, it will output “FizzBuzz”.
Note that many of these solutions rely on the modulo operator, which essentially gives you the remainder of diving a number by another number. So for example,
3 % 2 will give a result of 1, because 2 goes into 3 once, with a remainder of 1. This allows us to easily calculate if a number is divisible by another number, by doing things like
number % 3 === 0 to determine if the number is divisible by 3 (and should thus trigger “Fizz”).
Solution #1: If statements
“FizzBuzz” is one of those rare cases where the simplest approach isn’t actually half bad. Simply loop through the supplied number range, and conduct an if statement for each of the 3 potential strings, or output the number if none match:
Solution #2: Concatenation
Although this code works great, there is an area where we can optimise. Rather than do 3 potential checks, we can actually just do 2, and concatenate the answers instead. In other words, rather than check if it’s a multiple of both 3 and 5, then 3, and then 5, we can instead check if it’s a multiple of 3, adding “Fizz” to a pre-initialised string if so, and then also check if it’s a multiple of 5, adding “Buzz” to the same string if so. This allows us to calculate “Fizz”, “Buzz” and “FizzBuzz” with only 2 checks:
Solution #3: Counters
For a bit of a change, here’s another method of getting the answer without using the all important modulo operator. Instead of performing a calculation on every number, we can instead increment “Fizz” and “Buzz” counters as we move towards N. This way, we will know to trigger “Fizz” every time the counter hits 0, and will then reset the counter to 3, and we do the same for “Buzz” with 5 (note that both counters start 1 value in as we are told to start at 1 rather than 0):
Solution #4: Extensible
A common complexity for this problem is that you’ll be asked to add additional triggers. For example, you might be told to replace all multiple of 7 with “Jazz”. Now, if you’ve use a standard if-based approach, this will mean adding an exponential number of if statements, which obviously isn’t ideal. However if you’re used concatenation, it isn’t so bad.
Nevertheless, what the questioner really wants to see is that you can make something extensible. So one good option is to pre-initialise a list of divisors and their associated keywords, so that we can loop through this list for each of the numbers, like so:
Spoiler alert: The first multiple of 3, 5 and 7 is 105, in case you were wondering.