412. Fizz Buzz
412. Fizz Buzz
题目
Given an integer n
, return a string arrayanswer
(1-indexed) where:
answer[i] == "FizzBuzz"
ifi
is divisible by3
and5
.answer[i] == "Fizz"
ifi
is divisible by3
.answer[i] == "Buzz"
ifi
is divisible by5
.answer[i] == i
(as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output: ["1","2","Fizz"]
Example 2:
Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]
Example 3:
Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Constraints:
1 <= n <= 10^4
题目大意
给你一个整数 n
,找出从 1
到 n
各个整数的 Fizz Buzz 表示,并用字符串数组 answer
(下标从 1 开始 )返回结果,其中:
answer[i] == "FizzBuzz"
如果i
同时是3
和5
的倍数。answer[i] == "Fizz"
如果i
是3
的倍数。answer[i] == "Buzz"
如果i
是5
的倍数。answer[i] == i
(以字符串形式)如果上述条件全不满足。
示例 1:
输入: n = 3
输出:["1","2","Fizz"]
示例 2:
输入: n = 5
输出:["1","2","Fizz","4","Buzz"]
示例 3:
输入: n = 15
输出:["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
提示:
1 <= n <= 10^4
解题思路
- 初始化一个空数组
answer
,用于存储结果。 - 遍历从
1
到n
的每个数字,使用条件语句判断当前数字是否符合以下条件:- 如果同时是 3 和 5 的倍数,将
"FizzBuzz"
插入数组。 - 如果是 3 的倍数,将
"Fizz"
插入数组。 - 如果是 5 的倍数,将
"Buzz"
插入数组。 - 如果不满足以上条件,将数字本身(字符串形式)插入数组。
- 如果同时是 3 和 5 的倍数,将
- 返回结果数组。
我们可以进一步优化 可读性 和 效率,比如使用字符串拼接,减少条件判断次数,见优化版代码。
复杂度分析
- 时间复杂度:
O(n)
,遍历从1
到n
的所有整数,每个整数都只判断一次。 - 空间复杂度:
O(n)
,结果数组需要存储n
个元素。
代码
普通版
/**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function (n) {
let answer = [];
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
answer.push('FizzBuzz');
} else if (i % 3 === 0) {
answer.push('Fizz');
} else if (i % 5 === 0) {
answer.push('Buzz');
} else {
answer.push(i.toString());
}
}
return answer;
};
优化版
/**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function (n) {
let answer = [];
for (let i = 1; i <= n; i++) {
let str = '';
if (i % 3 === 0) str += 'Fizz';
if (i % 5 === 0) str += 'Buzz';
answer.push(str || i.toString());
}
return answer;
};
相关题目
题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
---|---|---|---|---|---|
1195 | 交替打印字符串 | 多线程 | 🟠 | 🀄️ 🔗 | |
2525 | 根据规则将箱子分类 | 数学 | 🟢 | 🀄️ 🔗 |