Algorithm
Problem Name: 412. Fizz Buzz
Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
ifi
is divisible by3
and5
.answer[i] == "Fizz"
ifi
is divisible by3
.answer[i] == "Buzz"
ifi
is divisible by5
.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
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string>res;
for(int i = 1; i < n + 1; i++){
string s = to_string(i);
if(i % 15 ==0) s = "FizzBuzz";
else if(i % 3 == 0) s = "Fizz";
else if(i % 5 == 0) s = "Buzz";
res.push_back(s);
}
return res;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
class Solution {
public List fizzBuzz(int n) {
List result = new ArrayList<>();
for (int i = 1; i < = n; i++) {
if (i % 15 == 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;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Javascript Programming
Code -
Javascript Programming
const fizzBuzz = function(n) {
const res = [];
for (let i = 1; i < = n; i++) {
res.push(single(i));
}
return res;
};
function single(num) {
let str = "";
if (num % 3 === 0) {
str += "Fizz";
}
if (num % 5 === 0) {
str += "Buzz";
}
if (str === "") {
str += num;
}
return str;
}
console.log(fizzBuzz(15));
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
num = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
num.append("FizzBuzz")
elif i % 3 == 0:
num.append("Fizz")
elif i % 5 == 0:
num.append("Buzz")
else:
num.append(str(i))
return num
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with C# Programming
Code -
C# Programming
using System.Collections.Generic;
namespace LeetCode
{
public class _0412_FizzBuzz
{
public IList < string> FizzBuzz(int n)
{
var answer = new List();
for (int num = 1; num < = n; num++)
{
var divisibleBy3 = (num % 3 == 0);
var divisibleBy5 = (num % 5 == 0);
var str = string.Empty;
if (divisibleBy3)
str += "Fizz";
if (divisibleBy5)
str += "Buzz";
if (string.IsNullOrEmpty(str))
str = num.ToString();
answer.Add(str);
}
return answer;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output