Problem 5:
发现把if(n>0)去了也是AC,因为要获得长度为n的数组,默认来说n是>=1的
Given number n. Print number from 1 to n. But:
- when number is divided by
3
, print"fizz"
. - when number is divided by
5
, print"buzz"
. - when number is divided by both
3
and5
, print"fizz buzz"
.
If n = 15
, you should return:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
注意点:
1、for 循环的index 和 vector 中的值 的对应关系要找好,若不是3或5的倍数,vector[index]应为index+1;
2、最后返回的是vector<string>类型的向量,要用to_string()函数将int 转为 string;
代码:
class Solution { public: /* * @param n: An integer * @return: A list of strings. */ vector<string> fizzBuzz(int n) { // write your code here vector<string> a(n); if(n>0){ for(int i = 0 ; i< n ; i++){ int x = (i+1)%3;int y = (i+1)%5; if(x == 0 && y == 0){ a[i] = "fizz buzz"; } else if(x == 0){ a[i] = "fizz"; } else if(y == 0){ a[i] = "buzz"; } else { a[i] = to_string(i+1); } } } return a; } };
发现把if(n>0)去了也是AC,因为要获得长度为n的数组,默认来说n是>=1的