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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值