LeetCode 412: Fizz Buzz
1. Actual Question
Problem Statement: Write a program that outputs the numbers from 1 to n. But for multiples of three, output "Fizz" instead of the number, and for the multiples of five, output "Buzz". For numbers that are multiples of both three and five, output "FizzBuzz".
Example:
Input: n = 15 Output: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
2. How to Solve the Question
- Loop through numbers from
1
ton
. - Use conditions to check divisibility:
- If divisible by both
3
and5
, add"FizzBuzz"
to the result. - If divisible by
3
, add"Fizz"
. - If divisible by
5
, add"Buzz"
. - Otherwise, add the number as a string.
- If divisible by both
- Store the results in a list and return it.
3. Approaches
Approach 1: Basic Iterative Solution
Check divisibility using the %
operator and append the correct string to the result list.
import java.util.ArrayList;
import java.util.List;
public class FizzBuzz {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
result.add("FizzBuzz");
} else if (i % 3 == 0) {
result.add("Fizz");
} else if (i % 5 == 0) {
result.add("Buzz");
} else {
result.add(String.valueOf(i));
}
}
return result;
}
public static void main(String[] args) {
FizzBuzz fb = new FizzBuzz();
System.out.println(fb.fizzBuzz(15));
}
}
Approach 2: String Concatenation
Instead of checking divisibility separately, build the string by concatenating "Fizz" and "Buzz" when conditions match.
import java.util.ArrayList;
import java.util.List;
public class FizzBuzzConcat {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
StringBuilder sb = new StringBuilder();
if (i % 3 == 0) sb.append("Fizz");
if (i % 5 == 0) sb.append("Buzz");
if (sb.length() == 0) {
result.add(String.valueOf(i));
} else {
result.add(sb.toString());
}
}
return result;
}
public static void main(String[] args) {
FizzBuzzConcat fb = new FizzBuzzConcat();
System.out.println(fb.fizzBuzz(15));
}
}
Approach 3: HashMap to Handle Rules
Store the rules (3 -> "Fizz"
, 5 -> "Buzz"
) in a HashMap to make it easy to add more rules in the future.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FizzBuzzHashMap {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
Map<Integer, String> fizzBuzzMap = new HashMap<>();
fizzBuzzMap.put(3, "Fizz");
fizzBuzzMap.put(5, "Buzz");
for (int i = 1; i <= n; i++) {
StringBuilder sb = new StringBuilder();
for (Integer key : fizzBuzzMap.keySet()) {
if (i % key == 0) {
sb.append(fizzBuzzMap.get(key));
}
}
if (sb.length() == 0) {
result.add(String.valueOf(i));
} else {
result.add(sb.toString());
}
}
return result;
}
public static void main(String[] args) {
FizzBuzzHashMap fb = new FizzBuzzHashMap();
System.out.println(fb.fizzBuzz(15));
}
}