LeetCode: 412 Fizz Buzz(easy)
题目:
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 class Solution { 2 public: 3 vector<string> fizzBuzz(int n) { 4 vector<string> result; 5 for(int i = 1; i < n+1; i++){ 6 if ((i%3 == 0)&&(i%5 == 0)) 7 result.push_back("FizzBuzz"); 8 else if ((i%3 != 0)&&(i%5 == 0)) 9 result.push_back("Buzz"); 10 else if ((i%3 == 0)&&(i%5 != 0)) 11 result.push_back("Fizz"); 12 else 13 result.push_back(to_string(i)); 14 } 15 return result; 16 } 17 };
别人的:
1 class Solution { 2 public: 3 vector<string> fizzBuzz(int n) { 4 vector<string> res; 5 for(int i=1; i<=n; i++){ 6 string s; 7 if(i%3==0) s = "Fizz"; 8 if(i%5==0) s += "Buzz"; 9 if(s.empty()) s = to_string(i); 10 res.push_back(s); 11 } 12 return res; 13 } 14 };