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" ]
输入一个正整数n,返回相应长度的string向量,每一位上对应是从1到n的数字,当能被3整除时用Fizz代替;能被5整除时用Buzz代替;能被3和5同时整除时同FizzBuzz代替。
重点:int转为string。使用string to_string(int)函数。
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> ans(n);
for(int i=1;i<=n;i++)
{
if(i%15==0)ans[i-1]="FizzBuzz";
else if(i%3==0)ans[i-1]="Fizz";
else if(i%5==0)ans[i-1]="Buzz";
else ans[i-1]=to_string(i);
}
return ans;
}
};