Question

Write a program that prints the numbers from 1 to 100. But for multiples of three print Fizz instead of the number and for the multiples of five print Buzz. For numbers which are multiples of both three and five print FizzBuzz

Example

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16

Buzz

Solution in Java

public class FizzBuzz {

    public static void main(String[] args) {
        printFizzBuzz(100);
    }

    public static void printFizzBuzz(int n) {
        for (int i = 1; i <= n; i++) {
            System.out.println(fizzBuzz(i));
        }
    }

    public static String fizzBuzz(int number) {
        String res = "";
        if (divBy(number, 3)) res += "Fizz";
        if (divBy(number, 5)) res += "Buzz";
        if (res.equals("")) return String.valueOf(number);
        return res;
    }

    public static boolean divBy(int first, int by) {
        if (by == 0) return false;
        int result = first / by;
        if (result * by  == first) return true;
        return false;
    }

}