Write A program this outputs the string representation of numbers from 1To n.but forMultiples of three it should output "Fizz" instead of the number and forthe multiples of five output "Buzz". For numbers which is 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"]
Solution 1:
1 Public classSolution {2 PublicList<string> Fizzbuzz (intN) {3list<string> res =NewArraylist<string>();4 for(intI=1; i<=n; i++) {5 if(i%3==0 && i%5==0) res.add ("Fizzbuzz");6 Else if(i% 3 = = 0) res.add ("Fizz");7 Else if(i% 5 = = 0) res.add ("Buzz");8 ElseRes.add (integer.tostring (i));9 }Ten returnRes; One } A}
Solution with out using%
1 Public classSolution {2 PublicList<string> Fizzbuzz (intN) {3list<string> ret =NewArraylist<string>(n);4 for(intI=1,fizz=0,buzz=0;i<=n; i++){5fizz++;6buzz++;7 if(Fizz==3 && buzz==5){8Ret.add ("Fizzbuzz");9Fizz=0;TenBuzz=0; One}Else if(fizz==3){ ARet.add ("Fizz"); -Fizz=0; -}Else if(buzz==5){ theRet.add ("Buzz"); -Buzz=0; -}Else{ - Ret.add (string.valueof (i)); + } - } + returnret; A } at}
Leetcode:fizz Buzz