DEV Community

talent
talent

Posted on

#2.Basic algorithms problems for frontend developers.

FizzBuzz algo problem.
1 in 4 interview questions on solving algorithms, is about the fizzbuzz pattern.

It sounds so fancy but all what it is, just finding out how many times a number is included in a bigger number.

In other words if a number is a multiple of another number.

JavaScript has the % module operator which tells you exactly that.

For example, 10 % 2 will be 0, because 2 is included 5 times in 10.

Instead, if we had 11 % 2, the answer will be 1. Which means is not a fizzbuzz result ;)

const num = 20;
/* FizzBuzz question:  Find out which number
 between 1 and a given number is a multiple
  of 5 and a mutiple of 4!
 If num is multiple of 5 and multiple of
  4 print 'fizzbuzz' to the console.log
if num is multiple only of 4 print 'fizz'. 
If instead is multiplwe only of 6 print 'buzz'. */

const fizzbuzz = n => {
  /* loop trough the number starting from 
  1 (because 0 will give us falsy values) */
  for (let i = 1; i <= n; i++) {
    // if 5 and 4 are multiples of i, print fizzbuzz
    if (i % 5 === 0 && i % 4 === 0) {
      console.log(i, 'fizzbuzz');
      // if only 5 is multiple of i print 'fizz'
    } else if (i % 5 === 0) {
      console.log(i, 'fizz');
      // if only 4 is multiple of i print 'buzz'
    } else if (i % 4 === 0) {
      console.log(i, 'bizz');
      /* if nither 5 or 4 are not multiple 
      of i print 'no fizz and no buzz here' */
    } else {
      console.log(i, 'no fizz and no buzz here');
    }
  }
};

fizzbizz(num);```


Enter fullscreen mode Exit fullscreen mode

Discussion (0)