Print 1..n, but "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
Check the combined case first (divisible by 15, or by both 3 and 5), otherwise the 3-check fires before the combined case. A cleaner variant builds a string from the applicable rules and prints the number only when the string is empty — extensible and bug-free. O(n).
public static void fizzBuzz(int n) {
for (int i = 1; i <= n; i++) {
String out = "";
if (i % 3 == 0) out += "Fizz";
if (i % 5 == 0) out += "Buzz";
System.out.println(out.isEmpty() ? String.valueOf(i) : out);
}
}function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
let out = '';
if (i % 3 === 0) out += 'Fizz';
if (i % 5 === 0) out += 'Buzz';
console.log(out || i);
}
}def fizz_buzz(n):
for i in range(1, n + 1):
out = ('Fizz' if i % 3 == 0 else '') + ('Buzz' if i % 5 == 0 else '')
print(out or i)FizzBuzz filters candidates who cannot translate simple rules into code; the string-building form mirrors maintainable rule engines.
A candidate writes if %3 else if %5 else if %15. What is wrong?