這題算是滿簡單的大部分寫法都差不多 , 所以寫個 linq 版本的 , 關鍵就是用 Enumerable 的 Range 產生出資料, 搭配 Select 進行 ReMapping 即可
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Solution { public IList<string> FizzBuzz(int n) { var nums = Enumerable.Range( 1, n ).Select( x => { if (x % 3 == 0 && x % 5 == 0) return "FizzBuzz"; if (x % 3 == 0) return "Fizz"; if (x % 5 == 0) return "Buzz"; return x.ToString(); } ).ToList(); return nums; } }
|
常見寫法 , 注意要把 3 & 5 擋在最前面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class Solution { public IList<string> FizzBuzz(int n) { var nums = Enumerable.Range( 1, n ); List<string> list = new List<string>( ); foreach (var item in nums) { if (item % 3 == 0 && item % 5 == 0) { list.Add( "FizzBuzz" ); continue; } if (item % 3 == 0) { list.Add( "Fizz" ); continue; } if (item % 5 == 0) { list.Add( "Buzz" ); continue; }; list.Add( item.ToString( ) ); }
return list; } }
|