Fizz Buzz problem (add elements to vector, int to string)

Enumeration method: see all possibilities

Give you an integer n. Print each number from 1 to n according to the following rules:
If the number is divisible by 3, print fizz.
If the number is divisible by 5, print buzz.
If the number is divisible by both 3 and 5, Print fizz buzz
e.g. n = 15, return an array of strings:
[
"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;
    }

Explanation of knowledge points:
1. Add an element at the end of Vector (the parameter is the value to be inserted): push_back()
2. Int variable string
to_string() method:
long/long long/float/double, etc. can use to_string() Convert to string
string stream method :

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

Implement any type of conversion

#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;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521657&siteId=291194637