跳至主要內容

412. Fizz Buzz


412. Fizz Buzz

🟢   🔖  数学 字符串 模拟  🔗 力扣open in new window LeetCodeopen in new window

题目

Given an integer n, return a string arrayanswer (1-indexed) where:

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • 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 ,找出从 1n 各个整数的 Fizz Buzz 表示,并用字符串数组 answer下标从 1 开始 )返回结果,其中:

  • answer[i] == "FizzBuzz" 如果 i 同时是 35 的倍数。
  • answer[i] == "Fizz" 如果 i3 的倍数。
  • answer[i] == "Buzz" 如果 i5 的倍数。
  • 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

解题思路

  1. 初始化一个空数组 answer,用于存储结果。
  2. 遍历从 1n 的每个数字,使用条件语句判断当前数字是否符合以下条件:
    • 如果同时是 3 和 5 的倍数,将 "FizzBuzz" 插入数组。
    • 如果是 3 的倍数,将 "Fizz" 插入数组。
    • 如果是 5 的倍数,将 "Buzz" 插入数组。
    • 如果不满足以上条件,将数字本身(字符串形式)插入数组。
  3. 返回结果数组。

我们可以进一步优化 可读性效率,比如使用字符串拼接,减少条件判断次数,见优化版代码。

复杂度分析

  • 时间复杂度O(n),遍历从 1n 的所有整数,每个整数都只判断一次。
  • 空间复杂度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;
};

相关题目

题号标题题解标签难度力扣
1195交替打印字符串多线程🟠🀄️open in new window 🔗open in new window
2525根据规则将箱子分类数学🟢🀄️open in new window 🔗open in new window