The "Fizz-Buzz test" is an interview question designed to help filter out the 99.5% of programming job candidates who can't seem to program their way out of a wet paper bag. The text of the programming assignment is as follows:
"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”."
Method 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
}
}
Method 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
string str = "";
if (i % 3 == 0)
{
str += "Fizz";
}
if (i % 5 == 0)
{
str += "Buzz";
}
if (str.Length == 0)
{
str = i.ToString();
}
Console.WriteLine(str);
}
Console.ReadLine();
}
}
}
Method 3 (Using Linq)
using System;
using System.Linq;
namespace fizzbuzz
{
class Program
{
static void Main(string[] args)
{
Enumerable.Range(1,100).ToList()
.ForEach(x =>
{
Console.WriteLine("{0}{1}{2}",
x % 3 == 0 ? "Fizz" : "",
x% 5 == 0 ? "Buzz" : "",
x % 3 != 0 && x % 5 != 0 ? x.ToString() : "");
});
}
}
}
No comments:
Post a Comment