Fizz Buzz
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 1:
Input: n = 3 (1,2,3)
Output: ["1","2","Fizz"]
Example 2:
Input: n = 5 (1,2,3,4,5)
Output: ["1","2","Fizz","4","Buzz"]
Example 3:
Input: n = 15 (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) Method 1 : With using Modulo Division(%)
Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
fizzbuzz(n):
list=[];
for i from 1 to n:
if i%5==0 && i%3==0:
list.add("FizzBuzz");
else if i%3==0:
list.add("Fizz");
else if i%5==0:
list.add("Buzz");
else:
list.add(Integer.toString(i));
return list;
package bracecoder; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FizzBuzz { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); System.out.println("Enter a Number : "); int n=scan.nextInt(); List<String> res = fizzBuzz(n); System.out.println(res); } private static List<String> fizzBuzz(int n) { // TODO Auto-generated method stub List<String> res = new ArrayList(); for (int i = 1; i <= n; i++) { if (i % 3 == 0 && i % 5 == 0) { res.add("FizzBuzz"); } else if (i % 3 == 0) { res.add("Fizz"); } else if (i % 5 == 0) { res.add("Buzz"); } else { res.add(Integer.toString(i)); } } return res; } }
OUTPUT
Method 2: Without using Modulo Division(%)
ALGORITHM
fizzbuzz(n):
list=[];
i3=0;i5=0;
for i from 1 to n:
i3=++;i5++;
if i5==5 && i3==3:
list.add("FizzBuzz"); i3=0;i5=0;
else if i3==3:
list.add("Fizz"); i3=0;
else if i5==5:
list.add("Buzz"); i5=0;
else:
list.add(Integer.toString(i));
return list;
package bracecoder; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FizzBuzz { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); System.out.println("Enter a Number : "); int n=scan.nextInt(); List<String> res = fizzBuzz(n); System.out.println(res); } private static List<String> fizzBuzz(int n) { // TODO Auto-generated method stub List<String> res = new ArrayList(); int i3=0, i5=0; for (int i = 1; i <= n; i++) { i3++; i5++; if (i3==3 && i5==5) { res.add("FizzBuzz"); i3=0; i5=0; } else if (i3==3) { res.add("Fizz"); i3=0; } else if (i5==5) { res.add("Buzz"); i5=0; } else { res.add(Integer.toString(i)); } } return res; } }
OUTPUT