Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
if i
is divisible by 3
and 5
.answer[i] == "Fizz"
if i
is divisible by 3
.answer[i] == "Buzz"
if i
is divisible by 5
.answer[i] == i
(as a string) if none of the above conditions are true.
Example 1:
Input: n = 3 Output: ["1","2","Fizz"]
Example 2:
Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]
Example 3:
Input: n = 15 Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Constraints:
1 <= n <= 104
The Fizz Buzz problem requires generating a list of strings representing numbers from 1 to n. The rules are:
The most straightforward approach is to iterate through numbers 1 to n and apply the rules using modulo operator (%
). We check divisibility by 15 first to catch "FizzBuzz" cases, followed by divisibility by 3 and 5 individually. If none of these conditions are met, we convert the number to a string.
The following code snippets demonstrate this approach in several popular programming languages. The core logic remains consistent across all implementations.
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for i in range(1, n + 1):
if i % 15 == 0:
ans.append('FizzBuzz')
elif i % 3 == 0:
ans.append('Fizz')
elif i % 5 == 0:
ans.append('Buzz')
else:
ans.append(str(i))
return ans
This Python code uses a simple for
loop and if-elif-else
chain to check the divisibility conditions. The append()
method adds the appropriate string to the ans
list.
class Solution {
public List<String> fizzBuzz(int n) {
List<String> ans = new ArrayList<>();
for (int i = 1; i <= n; ++i) {
String s = "";
if (i % 3 == 0) s += "Fizz";
if (i % 5 == 0) s += "Buzz";
if (s.isEmpty()) s += i; //if s is empty then add the number
ans.add(s);
}
return ans;
}
}
The Java code is similar, using an ArrayList
to store the results. Note how the string s
is built incrementally.
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> ans;
for (int i = 1; i <= n; ++i) {
string s = "";
if (i % 3 == 0) s += "Fizz";
if (i % 5 == 0) s += "Buzz";
if (s.empty()) s = to_string(i);
ans.push_back(s);
}
return ans;
}
};
The C++ version utilizes a vector<string>
and to_string()
for number conversion.
var fizzBuzz = function(n) {
let result = [];
for (let i = 1; i <= n; i++) {
let output = "";
if (i % 3 === 0) output += "Fizz";
if (i % 5 === 0) output += "Buzz";
result.push(output || i); //if output is empty push i
}
return result;
};
The JavaScript solution uses a similar iterative approach, with a concise way to handle the case where neither 3 nor 5 divides i
.
This solution is efficient and easy to understand, making it a good choice for solving the Fizz Buzz problem. More sophisticated approaches are generally unnecessary for this problem due to its simplicity and the already linear time complexity.