[C#][LeetCode][Easy] 412. Fizz Buzz

心得:

這題也滿簡單用迴圈跑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”.
答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

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;
}
}