Thursday 16 June 2016

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.

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,
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

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...