Method for FizzBuzz Problem
The method used here will be a simple greedy approach. We will check if the given conditions given above and then print the output accordingly. We will use the following steps to implement this algorithm.
- Declare the number.
- Check if the number is divisible by both 3 and 5. If yes then print FizzBuzz.
- Else check if the number is divisible by 3. If yes then print Fizz.
- Else check if number is divisible by 5. If yes then print Buzz.
- Else print the given number as it is.
The only condition here is we first have to check whether the number is divisible by both 5 and 3 or not as if we check for single number first it will become true and we will get wrong output.
Below is the implementation of FizzBuzz Program in Java:
// Java Program to implement
// FizzBuzz Problem
public class FizzBuzz {
public static void main(String[] args)
{
fizzBuzz(9);
fizzBuzz(25);
fizzBuzz(15);
fizzBuzz(4);
}
public static void fizzBuzz(int n)
{
// check if divisible by both 3 and 5.
if (n % 3 == 0 && n % 5 == 0) {
System.out.println("FizzBuzz");
}
// check if divisible by both 3.
else if (n % 3 == 0) {
System.out.println("Fizz");
}
// check if divisible by both 5.
else if (n % 5 == 0) {
System.out.println("Buzz");
}
// If not divisible by anything print the number as
// it is.
else {
System.out.println(n);
}
}
}
Output:
Fizz
Buzz
FizzBuzz
4
Complexity of the above Method:
Time complexity: O(1)
Space complexity: O(1)
Fizz Buzz Program in Java
FizzBuzz is a game popular amongst kids that also teaches them the concept of division. In recent times it has become a popular programming question. Following is the problem statement for the FizzBuzz problem.
Examples:
Input: 9
Output: Fizz
Explanation: The number is divisible by 3 only.Input: 25
Output: Buzz
Explanation: The number is divisible by 5 only.Input: 15
Output: FizzBuzz
Explanation: The number is divisible by both 3 and 5.Input: 4
Output: 4
Explanation: The number is not divisible by both 3 and 5.
We will use the following method to solve this problem statement.