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”.
java(5ms):
1 public class Solution { 2 public List<String> fizzBuzz(int n) { 3 ArrayList<String> list = new ArrayList<String>() ; 4 for (int i = 1 ; i <= n ; i++){ 5 if (i%3==0 && i%5!=0) 6 list.add("Fizz") ; 7 else if (i%3!=0 && i%5==0) 8 list.add("Buzz") ; 9 else if (i%3==0 && i%5==0) 10 list.add("FizzBuzz") ; 11 else 12 list.add(""+i) ; 13 } 14 15 return list; 16 } 17 }
java(6ms):
1 public List<String> fizzBuzz(int n) { 2 3 ArrayList<String> list = new ArrayList<String>() ; 4 int fizz = 0 ; 5 int buzz = 0 ; 6 for (int i = 1 ; i <= n ; i++){ 7 fizz++ ; 8 buzz++ ; 9 if (fizz == 3 && buzz == 5){ 10 list.add("FizzBuzz") ; 11 fizz = 0 ; 12 buzz = 0 ; 13 } 14 15 else if (buzz == 5){ 16 list.add("Buzz") ; 17 buzz = 0 ; 18 } 19 else if (fizz == 3){ 20 list.add("Fizz") ; 21 fizz = 0 ; 22 } 23 else 24 list.add(""+i) ; 25 26 } 27 28 return list; 29 30 }
C++(3ms):
1 class Solution { 2 public: 3 vector<string> fizzBuzz(int n) { 4 vector<string> res ; 5 int fizz = 0 ,buzz = 0 ; 6 for (int i = 1 ; i <= n ; i++){ 7 fizz++; 8 buzz++; 9 if (fizz==3 && buzz==5){ 10 res.push_back("FizzBuzz") ; 11 fizz=0; 12 buzz=0; 13 } 14 else if (fizz==3){ 15 res.push_back("Fizz") ; 16 fizz=0; 17 } 18 else if (buzz==5){ 19 res.push_back("Buzz") ; 20 buzz=0; 21 } 22 else 23 res.push_back(to_string(i)) ; 24 } 25 return res; 26 } 27 };