Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
[code lang="java"]
class Solution {
public List<String> fizzBuzz(int n) {
}
}
[code]
Idea – 1
Iterate from 1 through n, check different conditions. Time complexity is linear. Space complexity constant (ignoring output size).
[code lang="java"]
class Solution {
public List<String> fizzBuzz(int n) {
List<String> ans = new ArrayList<>();
if(n < 1)
{
return ans;
}
for(int x = 1; x <= n; ++x)
{
if(x%15 == 0)
{
ans.add("FizzBuzz");
}
else if(x%3 == 0)
{
ans.add("Fizz");
}
else if(x%5 == 0)
{
ans.add("Buzz");
}
else
{
ans.add(String.valueOf(x));
}
}
return ans;
}
}
[code]
Runtime: 1 ms, faster than 100.00% of Java online submissions for Fizz Buzz.Memory Usage: 36.2 MB, less than 99.97% of Java online submissions for Fizz Buzz.


