FizzBuzz!

I came across a FizzBuzz problem while trying to come up with some sample code.  The problem is pretty simple.

Write a program that prints the numbers from 1 to 100. But for multiples of 3 print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiple of both 3 and 5, print “FizzBuzz”.

Multiple sources said that only 1% of programmers could solve this problem.  That makes me think too many people call themselves programmers.

It took me about 10 minutes to come up with this in javascript:


for (var i=1; i <=100; i++) {
   var x = '';
   if (!(i%3)) {
      x += 'Fizz';
   }
   if (!(i%5)) {
      x += 'Buzz';
   }
   if (x.length == 0) {
      x = i;	
   } 
   document.write(x + "<br>");
}

That worked great.  You can see it at CodePen.  After I finished, I looked at some other answers and found a couple of ways to improve it.  Initially, I wanted to else if all the way through my options, but I had a brainfart and didn’t think of checking if it is divisible by 15.  You can also check to see if x is null and if it is, write i, but I didn’t want to do it that way.  Here is the final code (CodePen):


for (var i=1; i <=100; i++) {
    var x = '';
    if (!(i%15)) {
      x = 'FizzBuzz';
    } else if (!(i%3)) {
      x = 'Fizz';
    } else if (!(i%5)) {
      x = 'Buzz';
    } else {
      x = i;	
    } 
 document.write(x + "<br>");
}

I hope you enjoyed that. It was a fun exercise. I’ll probably write one in ColdFusion soon.