Write an algorithm that prints all numbers between 1 and n, replacing multiples
of 3 with the String Fizz, multiples of 5 with Buzz, and multiples of 15 with
FizzBuzz.
This question is popular, and one of the most used on Interview. Below is the code block of the problem,
of 3 with the String Fizz, multiples of 5 with Buzz, and multiples of 15 with
This question is popular, and one of the most used on Interview. Below is the code block of the problem,
public static List<String> fizzBuzz(final int n) {
final List<String> toReturn = new ArrayList<>(n);
for (int i = 1; i <= n; i++) {
if(i % 15 == 0) {
toReturn.add("FizzBuzz");
} else if (i % 3 == 0) {
toReturn.add("Fizz");
} else if (i % 5 == 0) {
toReturn.add("Buzz");
} else {
toReturn.add(Integer.toString(i));
}
}
return toReturn;
}
No comments:
Post a Comment