1.題目大意
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”.
給定一個數n,要求寫出代表1到n的字符串,其中能被3整除的輸出 “Fizz”,能被5整除的輸出 “Buzz”,同時被3和5整除的輸出 “FizzBuzz”。
2.思路
思路非常簡單。是個人應該都能做出來。但有幾點可以學習一下,一個是C++中vector的應用(可以參考這篇文章),另一個是C++中int轉string的方法。
下面是int轉string的幾種思路:
(1)利用stringstream:
使用stringstream的時候要注意加#include"sstream"。比如說我要把int類型的23轉為string類型,那么我可以這樣實現:
int a=23;
stringstream ss;
ss<<a;
string s1 = ss.str();
(2)利用sprintf int->char[]
(3)利用itoa int->char[]
(4)利用to_string (詳見本題AC代碼)
3.代碼
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> s;
for(int i=1;i<=n;i++)
{
if(i%15==0)
s.push_back("FizzBuzz");
else if(i%3==0)
s.push_back("Fizz");
else if(i%5==0)
s.push_back("Buzz");
else
s.push_back(to_string(i));
}
return s;
}
};
