Lintcode 9 Fizz Buzz
Given number n. Print number from 1 to n. But:
when number is divided by 3, print “fizz”.
when number is divided by 5, print “buzz”.
when number is divided by both 3 and 5, print “fizz buzz”.
Analysis:
This is a very basic interview question for software engineer job. Basically, we can start by the most intuitive solutions:
- Check i is divided by 3, not divided by 5, print “fizz”
- Check i is divided by 5, not divided by 3, print “fuzz”
- Check i is both divided by 3 and 5, print “fizz buzz”
- Other numbers, print out the number
Disadvantages: too much % checking. We can improve this by starting from checking 3 and 5, then 5, then 3, then other numbers. The process is like:
- Check i is both divided by 3 and 5, print “fizz buzz”
- Check i is divided by 3, not divided by 5, print “fizz”
- Check i is divided by 5, not divided by 3, print “fuzz”
- Other numbers, print out the number
This Code is written in below:
for (int i = 1; i <= n; i++) {
// Start from 15
if (i % 15 == 0) {
System.out.println("fizz buzz");
} else if (i % 5 == 0) { // check with 5
System.out.println("buzz");
} else if (i % 3 == 0) { // check with 3
System.out.println("fizz");
} else { // print out other nums
System.out.println(i);
}
}
Alternative method:
In some interviews, the interviewer requires to use only two module and get the same result. To make this work, we can have a number k to indicate different situations. With different case of k, then print out different result.
for (int i = 1; i <= n; i++) {
int k = 1;
if (i % 3 == 0) k++;
if (i % 5 == 0) k += 2;
switch(k) {
case 1:
System.out.println(i);
break;
case 2:
System.out.println("fizz");
break;
case 3:
System.out.println("buzz");
break;
case 4:
System.out.println("fizzbuzz");
break;
}
}
If we take the n to be 20, then the result is:
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz