LinkedIn Technical Round Question Fizz-Buzz Problem Using Java via LeetCode
FizzBuzz is a game that is popular among kids. By playing this, kids learn the division. Now, the FizzBuzz game has become a popular programming question that is frequently asked in Java programming interviews. In this section, we will learn how to create a FizzBuzz program in Java.
Rules of the FizzBuzz Game
The rules of the FizzBuzz game are very simple.
Say Fizz if the number is divisible by 3.
Say Buzz if the number is divisible by 5.
Say FizzBuzz if the number is divisible by both 3 and 5.
Return the number itself, if the number is not divisible by 3 and 5.
There are two ways to create FizzBuzz program in Java:
- Using else-if Statement
- Using Java 8
The method parses two parameters:
startInclusive : It is the initial value.
endInclusive : The inclusive upper bound
Output:
Enter the number: 40
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz
Note that, in the above program the logic for FizzBuzz is adjusted into one line by using the ternary operator. It reduces the line of code. We have printed Fizz if the number is multiple of 3, prints Buzz if the number is multiple of 5, prints FizzBuzz if the number is multiple of 3 and 5, else prints the number itself.
Music by Praz Khanal from Pixabay
#java #leetcode #codingtutorial