The famous FizzBuzz problem

Today I came across the Developer survey results 2019 from stackoverflow.com. One of the questions asked in the survey was whether you have ever been asked to solve the FizzBuzz problem in an interview. I recollected that four years back I had coded this in an online test for an interview. I could write the code for it correctly, but the time I took was more than I should have. I decided to give it a try again today, and I feel this time I completed it in lesser time than in my attempt at the interview, but it was again not too great an improvement. After my code ran successfully, I looked over the internet for solutions posted by other people, in order to gain insights from them. I found my solution took a somewhat different approach. I couldn't find any solution that took the same approach as mine ,so I thought it would be nice to post my version of the solution.
For those who don't remember the FizzBuzz problem, here is it :
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”.
Here is my solution :

public class FizzBuzz {

 public static void main(String[] args) {
  for(int i = 1; i <= 100; i++) {
   boolean flag = false;
   if(i % 3 == 0) {
    System.out.print("Fizz");
    flag = true;
   }
   if(i % 5 == 0) {
    System.out.print("Buzz");
    flag = true;
   }
   if(!flag) {
    System.out.print(i);
   }
   System.out.println();
  }
 }
}

Below is the output:

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
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

Please post a comment if you find the solution good or helpful . Please post a comment in case you see any shortcomings of this approach, I would love to know about it and enhance my knowledge in the process.

Comments

Popular posts from this blog

Day#3 of Java Programming Practice- Longest word of a Sentence

Book Review: Those Pricey Thakur Girls

Day# 5 of Java Programming Practice- Change the first letter of each word in a sentence to Uppercase.