Problem Solving | Fizz Buzz Problem

Problem Solving | Fizz Buzz Problem

Subscribe to my newsletter and never miss my upcoming articles

Question:

Write a program that prints the numbers from 1 to 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"

Optimal Solution:

O(n)

function FizzBuzz(target) {
    for (var i = 1; i <=target; i++) {
        var result = "";
        if (i%3 === 0) result += "Fizz";        
        if (i%5 === 0) result += "Buzz";

        console.log(result || i);
    }
}

Even shorter version, using the same logic and ternary operators:

function FizzBuzz(target) {
for(let i=0;i<target;)console.log((++i%3?'':'fizz')+(i%5?'':'buzz')||i)
}
 
Share this