412. Fizz Buzz
On LeetCode ->Problem¶
Return a list of strings for numbers 1..n:
"FizzBuzz"if the number is divisible by15"Fizz"if divisible by3"Buzz"if divisible by5- otherwise the number itself as a string
Example:
n = 6 -> ["1", "2", "Fizz", "4", "Buzz", "Fizz"]
Key trick¶
Check the combined case first:
- divisibility by
15 - then
3 - then
5
This avoids incorrectly returning "Fizz" or "Buzz" for multiples of both.
Trap¶
Common mistakes:
- checking
3and5before15 - using
0..n-1instead of1..n - returning integers instead of strings
Why is it interesting?¶
It is simple but tests:
- careful condition ordering
- off-by-one handling
- clean loop and string construction
Python solution¶
class Solution:
def fizzBuzz(self, n: int) -> list[str]:
res = []
# Build the result from 1 to n inclusive.
for i in range(1, n + 1):
if i % 15 == 0:
res.append("FizzBuzz")
elif i % 3 == 0:
res.append("Fizz")
elif i % 5 == 0:
res.append("Buzz")
else:
res.append(str(i))
return res
Comment on my solution¶
Not provided.