LeetCode problem#412
Fizz Buzz
Solved in 1 languageJava
Solution
1class Solution {
2 public List<String> fizzBuzz(int n) {
3 List<String> list = new ArrayList<String>(n);
4
5 for (int i = 1; i <= n; i++) {
6 if (i % 3 == 0 && i % 5 == 0) {
7 list.add("FizzBuzz");
8 }
9 else if (i % 3 == 0) {
10 list.add("Fizz");
11 }
12 else if (i % 5 == 0) {
13 list.add("Buzz");
14 }
15 else {
16 list.add("" + i);
17 }
18 }
19
20 return list;
21 }
22}How it works
The problem presented is a classic coding challenge known as "Fizz Buzz". The objective is to print numbers from 1 to n, but for multiples of 3, the output should be "Fizz" instead of the number, for multiples of 5, it should be "Buzz", and for numbers that are multiples of both 3 and 5, it should be "FizzBuzz".
Let's break down the provided solution step-by-step:
Class and Method Definition
class Solution {
public List<String> fizzBuzz(int n) {- We define a public class
Solutionwhich has a methodfizzBuzzthat takes an integernas input. - The method will return a list of strings.
List Initialization
List<String> list = new ArrayList<String>(n);- An
ArrayListcalledlistis created to hold the results. We initialize its capacity ton, which is the maximum size it might reach (though its actual size will be determined as we add elements).
Loop Through Numbers
for (int i = 1; i <= n; i++) {- A
forloop is used to iterate over each numberistarting from 1 up to and includingn.
FizzBuzz Logic
Inside the loop, we check the conditions for each number to decide what to add to the list:
1if (i % 3 == 0 && i % 5 == 0) {
2 list.add("FizzBuzz");
3}
4else if (i % 3 == 0) {
5 list.add("Fizz");
6}
7else if (i % 5 == 0) {
8 list.add("Buzz");
9}
10else {
11 list.add("" + i);
12}- Multiple of both 3 and 5: If
iis a multiple of both (i.e.,i % 3 == 0 && i % 5 == 0), we append"FizzBuzz"tolist. - Multiple of 3: If
iis only a multiple of 3 (i.e.,i % 3 == 0), we append"Fizz"tolist. - Multiple of 5: If
iis only a multiple of 5 (i.e.,i % 5 == 0), we append"Buzz"tolist. - Neither: If
iis not a multiple of either 3 or 5, we simply add the number itself (converted to a string) to the list withlist.add("" + i).
Return the Result
return list;- Finally, after completing the loop, the method returns the list of strings containing the "FizzBuzz" results for each number from 1 to
n.
Example
If n is 15, the output of fizzBuzz(15) would be:
- 1,
- 2,
- "Fizz" (for 3),
- "Buzz" (for 5),
- "Fizz" (for 6),
- "FizzBuzz" (for 15),
- etc.
The final output will look like this:
["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]Overall, this implementation effectively solves the Fizz Buzz problem with a straightforward approach using simple condition checks.
Written by AI from the code above, so double-check anything important.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.