public class Solution { public IList<string> FizzBuzz(int n) { var list = new List<string>(); for (int i = 1; i <= n; i++) { if (i % 15 == 0) { list.Add("FizzBuzz"); } else if (i % 5 == 0) { list.Add("Buzz"); } else if (i % 3 == 0) { list.Add("Fizz"); } else { list.Add(i.ToString()); } } return list; } }
https://leetcode.com/problems/fizz-buzz/#/description
C++代码:
class Solution { public: vector<string> fizzBuzz(int n) { vector<string> V; for (int i = 1; i <= n; i++) { if (i % 3 == 0 && i % 5 == 0) { V.push_back("FizzBuzz"); } else if (i % 3 == 0) { V.push_back("Fizz"); } else if (i % 5 == 0) { V.push_back("Buzz"); } else { stringstream stream; stream << i; V.push_back(stream.str()); } } return V; } };
Python代码:
1 class Solution: 2 def fizzBuzz(self, n: int) -> 'List[str]': 3 result = [] 4 for i in range(1,n+1): 5 if i % 3 == 0 and i % 5 == 0:#同时可以被3和5整除 6 result.append('FizzBuzz') 7 elif i % 3 == 0: 8 result.append('Fizz')#只能被3整除 9 elif i % 5 == 0: 10 result.append('Buzz')#只能被5整除 11 else: 12 result.append(str(i))#既不能被3整除,也不能被5整除 13 return result