Skip to content

Instantly share code, notes, and snippets.

@kmdarshan
Created May 22, 2019 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmdarshan/be310634e6fce034ccf1c0d53fd843e8 to your computer and use it in GitHub Desktop.
Save kmdarshan/be310634e6fce034ccf1c0d53fd843e8 to your computer and use it in GitHub Desktop.
Fizzbuzz problem in swift
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
func fizzBuzz(_ n: Int) -> [String] {
var fizzBuzzArray = [String]()
for i in 1...n
{
if((i%3 == 0) && (i%5 == 0) && (i>=3) && (i>=5))
{
fizzBuzzArray.append("FizzBuzz")
}
else if(i%3 == 0 && (i>=3))
{
fizzBuzzArray.append("Fizz")
}
else if(i%5 == 0 && (i>=5))
{
fizzBuzzArray.append("Buzz")
}
else
{
fizzBuzzArray.append(String(i))
}
}
return fizzBuzzArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment