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"
.
Example
If n = 15
, you should return:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
解题思路:
1、非常简单,不过要对vector类的成员函数有所了解,最后一种情况需要将int型数据push_back进入,可是push_back()函数只接受它本身的string类型,不能直接传递,这里需要把int转换为string,用to_string()函数即可。
class Solution {
public:
/*
* @param n: An integer
* @return: A list of strings.
*/
vector<string> fizzBuzz(int n)
{
// write your code here
vector<string> temp;
for(int i=1;i<=n;i++)
{
if(i%3==0 && i%5==0)
{
temp.push_back("fizz buzz");
}
else if(i%3==0)
{
temp.push_back("fizz");
}
else if(i%5==0)
{
temp.push_back("buzz");
}
else
{
temp.push_back(to_string(i));
}
}
return temp;
}
};
JAVA代码:
public class Solution {
/**
* @param n: An integer
* @return: A list of strings.
*/
public List<String> fizzBuzz(int n) {
// write your code here
List<String> list = new ArrayList<>(n);
for(int i=1 ; i<=n ; i++){
if(i%3 == 0 && i%5 == 0){
list.add("fizz buzz");
}else if(i%3 == 0){
list.add("fizz");
}else if(i%5 == 0){
list.add("buzz");
}else{
list.add(Integer.toString(i)); //也可用String.valueOf(i)
}
}
return list;
}
}