0
点赞
收藏
分享

微信扫一扫

LeetCode刷题(113)~Fizz Buzz


题目描述

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

  1. 如果 n 是3的倍数,输出“Fizz”;
  2. 如果 n 是5的倍数,输出“Buzz”;
  3. 如果 n 同时是3和5的倍数,输出 “FizzBuzz”。

示例:

n = 15,

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

解答 By 海轰

提交代码

vector<string> fizzBuzz(int n) {
vector<string> res;
for(int i=1;i<=n;++i)
{
if(i%3==0&&i%5!=0)
res.push_back("Fizz");
else if(i%3!=0&&i%5==0)
res.push_back("Buzz");
else if(i%3==0&&i%5==0)
res.push_back("FizzBuzz");
else
res.push_back(to_string(i));
}
return res;
}

运行结果

LeetCode刷题(113)~Fizz Buzz_提交代码


提交代码

vector<string> fizzBuzz(int n) {
vector<string> res;
for(int i=1;i<=n;++i)
{
string temp;
if(i%3==0)
temp+="Fizz";
if(i%5==0)
temp+="Buzz";
if(temp=="")
temp=to_string(i);
res.push_back(temp);
}
return res;
}

运行结果

LeetCode刷题(113)~Fizz Buzz_提交代码_02

解答

Demo

vector<string> fizzBuzz(int n) {
vector<string> ans;

//Hash map to store all fizzbuzz mappings.
map<int, string> fizzBuzzDict = {
{3, "Fizz"},
{5, "Buzz"}
};

for (int num = 1; num <= n; ++num)
{
string numAnsStr = "";

for (auto key : fizzBuzzDict)
{
//If the num is divisible by key,
//then add the corressponding string mapping to current numAnsStr
if (num % key.first == 0)
numAnsStr += key.second;
}
//Not divisible by 3 or 5, add the number
if (numAnsStr == "")
numAnsStr += to_string(num);
// Append the current answer str to the ans list
ans.push_back(numAnsStr);
}
return ans;
}

运行结果

LeetCode刷题(113)~Fizz Buzz_leetcode_03

题目来源

链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xngt85/
来源:力扣(LeetCode)


举报

相关推荐

0 条评论