首页 > 学院 > 开发设计 > 正文

LeetCode题解:FizzBuzz

2019-11-14 11:15:49
字体:
来源:转载
供稿:网友

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"]

思路:

太简单。

题解:

std::vector<std::string> fizzBuzz(int n) {    std::vector<std::string> result(n);    for(int i = 1; i <= n; ++i) {        if (i % 3 && i % 5)            result[i - 1] = std::to_string(i);        else if (i % 3)            result[i - 1] = "Buzz";        else if (i % 5)            result[i - 1] = "Fizz";        else            result[i - 1] = "FizzBuzz";    }    return result;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表