心得:
這題也滿簡單用迴圈跑1~n,如果是3的的倍數則將Fizz
加入陣列,5的倍數則將Buzz
加入陣列,同時是3與5的倍數的話則將FizzBuzz
加入陣列,其餘則加入i。
題目:
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”.
答案:
public class Solution { public IList<string> FizzBuzz(int n) { List<string> ans = new List<string>(); for(int i = 1 ; i <= n ; i++ ){ if(i > 2){ if(i % 3 == 0 && i % 5 == 0){ ans.Add("FizzBuzz"); }else if(i % 3 == 0){ ans.Add("Fizz"); }else if(i % 5 == 0){ ans.Add("Buzz"); }else{ ans.Add(i.ToString()); } }else{ ans.Add(i.ToString()); } } return ans; } }