Tuesday, April 23, 2024
HomeC#Fixing FizzBuzz drawback in C#

Fixing FizzBuzz drawback in C#


FizzBuzz drawback is a straightforward algorithm take a look at given in interviews. I feel I acquired this at the very least 5 occasions. So you’ll most likely additionally obtain it at your following interview.

The issue appears like this:

Write a program that prints the quantity from 1 to N:

  • If an integer is divisible by 3, then print Fizz.
  • In case it’s divisible by 5, then print Buzz.
  • If the quantity is divisible by each 3 and 5, then print FizzBuzz.
  • In different instances, print the quantity.

Right here is an instance of a sequence:

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

Answer for FizzBuzz interview query

To unravel this drawback, you have to a for loop and an if-else assertion:

for (int i = 1; i <= N; i++)
{
   if (i % 15 == 0)
    {
        _textWriter.Write("FizzBuzz");
    }
    else if (i % 3 == 0)
    {
        _textWriter.Write("Fizz");
    }
    else if (i % 5 == 0)
    {
        _textWriter.Write("Buzz");
    }
    else
    {
        _textWriter.Write(i);
    }
    _textWriter.Write("n");
}

First, you examine if the quantity is divisible by 15 as a result of numbers which might be divisible by each 3 and 5 must be printed in a different way. Then you definately examine if it’s divisible by 3 or 5.

Right here you’ll find the repository that accommodates the answer.

One other resolution is to make use of provided that statements.

for (int i = 1; i <= 100; i++)  
{  
        string currentString = "";  
        if (i % 3 == 0)  
        {  
            currentString += "Fizz";  
        }  
        if (i % 5 == 0)  
        {  
            currentString += "Buzz";  
        }  
        _textWriter.WriteLine(currentString.Size==0?i.ToString():currentString);  
}

There are a number of methods to resolve this drawback. Be happy to seek out new methods. This drawback is fairly easy, however interviews love to make use of it as a result of it filters very quick the acceptable candidates.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments