All of you know the trivial fizzbuzz
question during the first junior interviews. In my case, it was more than write a solution. There were more requirements:
- Only two
if\else
statements. StringBuilder
required.- No
Map
,Collection
. - No ternary operator.
- Only Java core (8 or 11).
- You have only 5 minutes (in my case, but for you it doesn't matter).
My solution with three if
statements:
for (int i = 0; i <= 100; i++) {
if (i%3==0 && i%5==0) {
System.out.println("fizzBuzz");
} else if (i%5==0) {
System.out.println("Buzz");
} else if (i%3==0) {
System.out.println("fizz");
} else {
System.out.println(i);
}
}
But yeah, there are three 'if' and no StringBuilder
. Okay, let's see two 'if' example:
List<String> answer = new ArrayList<String>();
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(3, "Fizz");
map.put(5, "Buzz");
for (int num = 1; num <= n; num++) {
String s = "";
for (Integer key : map.keySet()) {
if (num % key == 0) {
s += map.get(key);
}
}
if (s.equals("")) {
s += Integer.toString(num);
}
answer.add(s);
}
And again it's wrong: two 'if' but no StringBuilder
.
Can I ask for a favor? Help me solve this problem.