Fizz Buzz 问题(vector添加元素,int转string)

枚举法:查看所有可能

给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
如果这个数被3整除,打印fizz.
如果这个数被5整除,打印buzz.
如果这个数能同时被3和5整除,打印fizz buzz
比如 n = 15, 返回一个字符串数组:
[
“1”, “2”, “fizz”,
“4”, “buzz”, “fizz”,
“7”, “8”, “fizz”,
“buzz”, “11”, “fizz”,
“13”, “14”, “fizz buzz”
]

vector<string> fizzBuzz(int n) {
        // write your code here
        vector<string> result;
        for(int i=1;i<=n;i++){
            if(i%3==0&&i%5==0)
                result.push_back("fizz buzz");
            else if(i%3==0)
                result.push_back("fizz");
            else if(i%5==0)
                result.push_back("buzz");
            else
                result.push_back(to_string(i));
        }
        return result;
    }

知识点讲解:
1.在Vector最后添加一个元素(参数为要插入的值):push_back()
2.int型变string
to_string()方法:
long/long long/float/double等都可以利用to_string()转换为string
字符串流方法

int n=1;
ostringstream  stream;
stream<<n;//向流中传值
stream.str();//返回string类型对象

实现任意类型的转换

#include<sstream>
 template<typename out_type, typename in_value>
    out_type convert(const in_value & t){
      stringstream stream;
      stream<<t;//向流中传值
      out_type result;//这里存储转换结果
      stream>>result;//向result中写入值
      return result;
    }

猜你喜欢

转载自blog.csdn.net/htt789/article/details/80064943