# FizzBuzz

March 7, 2021 3559

Input a positive integer N, return an array of strings with all the integers from 1 to N. But for multiples of 3, the array should have “Fizz” instead of the number. For the multiples of 5, the array should have “Buzz” instead of the number. For numbers that are multiples of 3 and 5 both, the array should have “FizzBuzz” instead of the number.

## Example

• ​​Input: 5

Output:1 2 Fizz 4 Buzz

• Input:15

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

### Explanation of above Examples

• In the first case, when we have taken input 5, it returned "1 2 Fizz 4 Buzz". Let's dry run-

1->1

2->2

3->Fizz(we need to replace the multiple of 3's with the "Fizz")

4->4

5->Buzz(we need to replace the multiples of 5's with the "Buzz")

Output-1 2 Fizz 4 Buzz

• In the second case, when we have taken input 5, it returned "1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz". Lets dry run-

​​​        1->1

2->2

3->Fizz(we need to replace the multiple of 3's with the "Fizz")

4->4

5->Buzz(we need to replace the multiples of 5's with the "Buzz")

6->Fizz(multiple of 3)

7->7

8->8

9->Fizz(multiple of 3)

10->Buzz(multiple of 5)

11->11

12->Fizz(multiple of 3)

13->13

14->14

15->FizzBuzz(we need to replace it the multiples of 3 and 5 both with the "FizzBuzz")

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

## Pseudocode​

Make a new empty list
function FizzBuzz(int n)
for i in 1 to N
if i modulus(%) 3==0 and i modulus(%) 5==0
else if i modulus(%) 5==0
else if i modulus(%) 3==0
else

•  Initialize an empty list. Iterate on the numbers from 1 ...N.
•  For every number, check if it is divisible by both 3 and 5, add FizzBuzz to the list.
•  Else, check if the number is divisible by 3, add Fizz to the list.
•  Else, check if the number is divisible by 5, add Buzz to the list.

## Program

package codesdope;
import java.util.*;
public class codesdope
{
public static List<String> fizzBuzz(int n)
{
ArrayList<String> str=new ArrayList<>();
for(int i=1;i<=n;i++)
{
if(i%3==0 && i%5==0)
{
}
else if(i%5==0)
{
}
else if(i%3==0)
{
}
else
{
}
}
return str;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
List<String> ans=fizzBuzz(n);
for(String s:ans)
System.out.print(s+" ");
}
}


​15

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

## Time complexity

Since we are adding 1 to N elements therefore time complexity of the algorithm would be O(N).

Liked the post?
Editor's Picks
0 COMMENT