Fizz Buzz

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:
n = 15,
Return:

[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

编写一个程序,输出从1到n的数字的字符串表示。

但是对于三倍的倍数,它应输出“Fizz”而不是数字,并输出五个输出“Buzz”的倍数。 对于三个和五个输出“FizzBuzz”的倍数的数字。

2,题目思路

对于这道题,在3倍、5倍、3倍且5倍的情况下, 输出对应的单词(行酒令)。

这道题也很简单,最简单的就是直接利用if和else操作来依次判断。不过根据题目,我们还可以对if进行优化,只需要先对3的倍数进行判断,再对5的倍数进行判断即可。

3,代码实现

static auto speedup = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> res;
        for(int i = 1;i<=n;i++){
            string tmp = "";
            if(i % 3 == 0)
                tmp += "Fizz";
            if(i % 5 == 0)
                tmp += "Buzz";
            if(tmp.empty())
                tmp = to_string(i);
            res.push_back(tmp);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值