leetcode 412 Fizz Buzz
给你一个整数 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"]
思路
按照题意做即可
代码
var fizzBuzz = function(n) {
const res = [];
for (let i = 1; i <= n; i++) {
if (i % 5 === 0 && i % 3 === 0) {
res[i - 1] = 'FizzBuzz';
} else if (i % 3 === 0) {
res[i - 1] = 'Fizz';
} else if (i % 5 === 0) {
res[i - 1] = 'Buzz';
} else {
res[i - 1] = '' + i;
}
}
return res;
};
复杂度分析:
- 时间复杂度: O(N)
- 空间复杂度:O(N)
FEATURED TAGS
前端开发
H5
JavaScript
设计模式
browser
jQuery
源码分析
生活
leetcode
Array
Stack
Queue
Linked List
剑指offer
Binary Search Tree
Binary Tree
Breadth-First Search
Depth-First Search
String
Set
Binary Search
Sliding Window
Backtracking
Dynamic Programming
Two Pointers
Union Find
Sort
Bit Operation
Recursion
Map
Graph
Search
Hash
LinkedList
复盘
QuickSort
Trie
Design
MinHeap
Traverse
Min Heap
Node.js
BackEnd
SQL
MySQL
Design Patterns
Network
计算机网络
Python
SVG