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
ifelse
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.
Advertisement
Answer
I’d say your solution with the map was very close, and nobody said “no arrays” 🙂
public class FizzBuzz { public static void main(String args[]) { StringBuilder sb = new StringBuilder(); Object[][] m = {{3, "Fizz"}, {5, "Buzz"}}; for (int i = 1; i <= 100; i++) { boolean found = false; for (Object[] o : m) { if (i % (int) (o[0]) == 0) { found = true; sb.append((String) (o[1])); } } if (!found) { sb.append(i); } sb.append(" "); } System.out.println(sb.toString()); } }
Which prints
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
Having said that, I think 5 minutes is a bit too strict for this kind of problem.