Posted by : Mostafa Mazhar

Problem : Fizz Buzz
Platform : leetcode
Language: Javascript
Link : Fizz Buzz

Fizz Buzz is a cool game where you will just simply start saying the numbers starting from 1 then 2 and 3 and so on, but there is a little tricky part, if the number is divisible by 3 you have to say "fizz" instead of the number.

Similarly if the number is divisible by 5 you have to say "Buzz".

Wiat.. we still have one last trick, if the number is divisible by 3 and also divisible by 5 (ex : 15) you have to say "FizzBuzz".

In this problem you are given (n) the number of elements in the game, you need to creat an array starting from 1 and emds at (n). and surely you have to follow the rules of the game.

Algorithm:
  • First creat an array to contain the numbers (answer).
  • Make for loop to start filling the array with (n) elements.
  • We use the modulo operator(%) to see if the number is divisible by 3 or 5 or both.
  • If the number is divisible by 3 and 5 we push : "FizzBuzz" into the array.
  • If it is divisible by 3 we push : "Fizz".
  • If it is divisible by 5 we push : "Buzz".
  • And if it is not divisible by any then we simply push the number as a string into the array.
  • When we finish the numbers we return the (answer) array.


Notice here we used the number 15 to cheek if the number is divisible by both 3 and 5, because if you think about it if a number is divisible by 3 and 5 it must be divisible by 15 (3 * 5).
You can also use the logical AND operator (&&) inside the if statment instead .

And we sarted the if statment with that condition because if we replace it with any other condition say the (3) for example, if the number is divisible by 3 and 5 the program will first check if the number is divisible by 3 (which is true) so it will push "Fizz" instead of "FizzBuzz" and exit the if statment without checking if it's also divisible by 5 or not.













Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © 2025 Quarks - Blogger Templates - Powered by Blogger - Designed by Johanes Djogan -