-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFizzBuzz.java
More file actions
41 lines (32 loc) · 975 Bytes
/
Copy pathFizzBuzz.java
File metadata and controls
41 lines (32 loc) · 975 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*Given an integer n, return a string array where:
If number is divisible by 3 → "Fizz"
If number is divisible by 5 → "Buzz"
If number is divisible by both 3 and 5 → "FizzBuzz"
Otherwise → number itself*/
import java.util.*;
class Solution {
public List<String> fizzBuzz(int n) {
// Store answer
List<String> result = new ArrayList<>();
// Traverse from 1 to n
for (int i = 1; i <= n; i++) {
// Divisible by both 3 and 5
if (i % 3 == 0 && i % 5 == 0) {
result.add("FizzBuzz");
}
// Divisible by 3
else if (i % 3 == 0) {
result.add("Fizz");
}
// Divisible by 5
else if (i % 5 == 0) {
result.add("Buzz");
}
// Otherwise add the number
else {
result.add(String.valueOf(i));
}
}
return result;
}
}