FizzBuzz
Given a number n, return the numbers from 1 to n written out as text, except that every multiple of 3 becomes "Fizz", every multiple of 5 becomes "Buzz", and any number that is a multiple of both becomes "FizzBuzz".
Examples
Example 1
- Input
- n = 15
- Output
- Fifteen answers come back, and only the last of them is a multiple of both.
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Example 2
- Input
- n = 5
- Output
- Nothing here is a multiple of both, so
["1","2","Fizz","4","Buzz"]"FizzBuzz"never appears.
The Code
function fizzBuzz(n) {
const out = [];
for (let i = 1; i <= n; i++) {
if (i % 15 === 0) out.push("FizzBuzz");
else if (i % 3 === 0) out.push("Fizz");
else if (i % 5 === 0) out.push("Buzz");
else out.push(String(i));
}
return out;
}
fizzBuzz(15);The first 11 calls, of 17. This one does not fit on a page.
Explanation
Each number meets the strictest rule first — both, then 3, then 5 — and is written out as itself only when all three miss.
- 1
At
i= 1:i % 15is not 0,i % 3is not 0 andi % 5is not 0, so the last branch runs and the number itself is pushed.1021324354i=1
out.push("1")
- 2
At
i= 3:i % 15is 3, so that test misses — buti % 3is 0, and the second branch runs.102132i=3
out.push("Fizz")
- 3
At
i= 5: the first two tests miss andi % 5is 0.Fizz04152i=5
out.push("Buzz")
- 4
At
i= 15:i % 15is 0 and the first branch runs. Had the test for 3 come first, it would have matched too and this would have been pushed as "Fizz".150both1i=15
out.push("FizzBuzz")
More like this
All arrays & loops examples (10) →- Array maximum Track the largest seen so far in a single pass.
- Two sum Remember every number you’ve seen; check for its complement.
- Product except self Everything to the left of a position, times everything to its right.
- Majority element Pair off disagreeing votes; the majority always survives.
- Merge intervals Sort by start, then either extend the last interval or begin a new one.
- Top K frequent Bucket values by their count, then read the buckets from the top.