Code Lab

FizzBuzz

EasyBasics10 min

Write a function fizzBuzz(n) that returns an array of strings for the numbers from 1 to n, in order. Each number gives one element of the array:

  • 'FizzBuzz' if the number divides by 3 and by 5 with no remainder (15, 30, 45, ...);
  • 'Fizz' if it divides by 3 but not by 5 (3, 6, 9, ...);
  • 'Buzz' if it divides by 5 but not by 3 (5, 10, 20, ...);
  • otherwise the number itself as a string: '7', not the number 7.

n is an integer, 0 or more. Both 1 and n are included. If n is 0, return an empty array [].

Examples

fizzBuzz(5)

Returns [ '1', '2', 'Fizz', '4', 'Buzz' ]

fizzBuzz(15)

Returns [ '1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz' ]

15 divides by 3 and by 5, so the last element is `'FizzBuzz'`.
fizzBuzz(0)

Returns []

Source

Loading the editor...
  1. InputfizzBuzz(5)
    Expected[ '1', '2', 'Fizz', '4', 'Buzz' ]
  2. InputfizzBuzz(15)
    Expected[ '1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz' ]
  3. InputfizzBuzz(0)
    Expected[]

Hidden tests run on Submit.