Algorithms – Fizz Buzz Algorithm

Imagine a series of a number from 1 to 10.

1 2 3 4 5 6 7 8 9 10

Fizz and Buzz refer to any number that’s a multiple of 3 and 5 respectively. In other words, if a number is divisible
by 3, it is substituted with fizz; if a number is divisible by 5, it is substituted with buzz. If a number is simultaneously
a multiple of 3 AND 5, the number is replaced with “fizz buzz.” In essence, it emulates the famous children game
“fizz buzz”.

int numbers = [1,2,3,4,5,… 15]

Below is solution –

1
2
3
4
5
6
7
8
9
10
11
for (int num : numbers {
if num % 3 == 0 && num % 5 == 0 {
print("\(num) fizz buzz")
} else if num % 3 == 0 {
print("\(num) fizz")
} else if num % 5 == 0 {
print("\(num) buzz")
} else {
print(num)
}
}

 

The better and advance version of solution is given below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for(int num : numbers){

if num % 15 == 0 {
print("\(num) fizz buzz")
} else if num % 3 == 0 {
print("\(num) fizz")
} else if num % 5 == 0 {
print("\(num) buzz")
} else {
print(num)
}
}

}

 

Reference *

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *