Open In App

Fizz Buzz Program in Java

Last Updated : 26 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

  1. Declare the number.
  2. Check if the number is divisible by both 3 and 5. If yes then print FizzBuzz.
  3. Else check if the number is divisible by 3. If yes then print Fizz.
  4. Else check if number is divisible by 5. If yes then print Buzz.
  5. 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
// 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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads