FizzBuzz
Problem
Read n and print the numbers from 1 to n, one on each line. For multiples of 3 print Fizz instead of the number. For multiples of 5 print Buzz. For multiples of both 3 and 5 print FizzBuzz.
Constraints
- 0 <= n <= 10^5
Examples
Input
5
Output
1 2 Fizz 4 Buzz
Solutions
The test for 15 must come first. If we test 3 first, the number 15 would print Fizz only. This is the same idea as the divisible-by-3-and-5 problem inside a loop.
/*
* Problem : Play FizzBuzz from 1 to n.
* Input : One integer n.
* Output : n lines.
* Approach: Check divisibility by 15 first.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
// Step 1: Visit every number from 1 to n.
for (int number = 1; number <= n; number++) {
// Step 2: Test the number divisible by both 3 and 5 (that means by 15) first.
if (number % 15 == 0) {
System.out.println("FizzBuzz");
} else if (number % 3 == 0) {
// Step 3: Multiples of 3 give Fizz.
System.out.println("Fizz");
} else if (number % 5 == 0) {
// Step 4: Multiples of 5 give Buzz.
System.out.println("Buzz");
} else {
// Step 5: All other numbers are printed as they are.
System.out.println(number);
}
}
}
}
Hints (1)
- What happens for 15 if you test 3 first?