Skip to main content

Solution of popular FizzBuzz coding puzzle in Java language

Introduction

FizzBuzz is one of the popular coding puzzles asked in a programming interview. In this post, we will learn its implementation using Java 8.

Problem

We have 1 to n Integers. Write a program that iterates over these integers, print Fizz if Integer is multiple of 3, print Buzz if Integer is multiple of 5, print FizzBuzz if Integer is multiple of both 3 and 5 else print the Integer.

 Solution



import java.util.stream.IntStream;

public class FizzBuzz {

 public static void main(String[] args) {
  int n = 100;
  
  IntStream.range(1, n).forEach( i -> {
   /* if( i % 3 == 0 && i % 5 == 0 ) is equivalent to i % 15 == 0 
    * and will reduce lines of code
    */
   if( i % 15 == 0) {
    System.out.println("FizzBuzz");
   }else if ( i % 3 == 0) {
    System.out.println("Fizz");
   }else if ( i % 5 == 0) {
    System.out.println("Buzz");
   }else {
    System.out.println(i);
   }
  });
 }
}

Note that multiple of 15 is multiple of both 3 and 5 and it will help in reducing the lines of code.

Conclusion

This puzzle tests the basic programming concept of a candidate. Hope it will help you in your future interview :)

Comments