412.数组下标的倍数 Fizz Buzz

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”.


Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

  1. /*
  2. Write a program that outputs the string representation of numbers from 1 to n.
  3. 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”.
  4. */
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. namespace Solution {
  10. class Solution {
  11. // bad version
  12. public IList<string> FizzBuzz(int n) {
  13. List<string> list = new List<string>();
  14. for (int index = 1; index <= n; index++) {
  15. if (index % 3 == 0 && index % 5 == 0) {
  16. list.Add("FizzBuzz");
  17. } else if (index % 3 == 0) {
  18. list.Add("Fizz");
  19. } else if (index % 5 == 0) {
  20. list.Add("Buzz");
  21. } else {
  22. list.Add(index.ToString());
  23. }
  24. }
  25. return list;
  26. }
  27. // using Linq
  28. public List<string> FizzBuzz(int n) {
  29. var list = Enumerable.Range(1, n).Select((i) => {
  30. if (i % 15 == 0) {
  31. return "FizzBuzz";
  32. } else if (i % 3 == 0) {
  33. return "Fizz";
  34. } else if (i % 5 == 0) {
  35. return "Buzz";
  36. } else {
  37. return i.ToString();
  38. }
  39. });
  40. return list.ToList();
  41. }
  42. // one line version,using Linq
  43. public List<string> FizzBuzz(int n) {
  44. return Enumerable.Range(1, n).Select(i => i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : i.ToString()).ToList();
  45. }
  46. }
  47. class Program {
  48. static void Main(string[] args) {
  49. var s = new Solution();
  50. List<string> res = s.FizzBuzz(15);
  51. Console.WriteLine(res);
  52. }
  53. }
  54. }






原文地址:https://www.cnblogs.com/xiejunzhao/p/41c51e6d3c43ef10a17fdb9d8e03c658.html