-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfizzbuzz.js
More file actions
97 lines (87 loc) · 1.87 KB
/
fizzbuzz.js
File metadata and controls
97 lines (87 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* Prints numbers from 1 to n with FizzBuzz rules.
*
* - Multiples of 3 → "fizz"
* - Multiples of 5 → "buzz"
* - Multiples of both 3 and 5 → "fizzbuzz"
*
* @example fizzBuzz(5)
* Output:
* 1
* 2
* fizz
* 4
* buzz
*/
/**
* Solution 1: Classic loop with conditionals
* Time: O(n)
* Space: O(1)
*
* @param {number} n
* @returns {void}
*/
const fizzBuzzClassic = (n) => {
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) console.log('fizzbuzz');
else if (i % 3 === 0) console.log('fizz');
else if (i % 5 === 0) console.log('buzz');
else console.log(i);
}
};
/**
* Solution 2: Cleaner logic using string building
* Time: O(n)
* Space: O(1)
*
* @param {number} n
* @returns {void}
*/
const fizzBuzzString = (n) => {
for (let i = 1; i <= n; i++) {
let output = '';
if (i % 3 === 0) output += 'fizz';
if (i % 5 === 0) output += 'buzz';
console.log(output || i);
}
};
/**
* Solution 3: Functional approach with Array.from()
* Time: O(n)
* Space: O(n)
*
* @param {number} n
* @returns {string[]}
*/
const fizzBuzzArray = (n) => {
return Array.from({ length: n }, (_, i) => {
const num = i + 1;
if (num % 15 === 0) return 'fizzbuzz';
if (num % 3 === 0) return 'fizz';
if (num % 5 === 0) return 'buzz';
return num.toString();
});
};
/**
* Solution 4: Using map after range creation
* Time: O(n)
* Space: O(n)
*
* @param {number} n
* @returns {string[]}
*/
const fizzBuzzMap = (n) => {
return [...Array(n).keys()].map(i => {
const num = i + 1;
let result = '';
if (num % 3 === 0) result += 'fizz';
if (num % 5 === 0) result += 'buzz';
return result || num.toString();
});
};
module.exports = {
fizzBuzzClassic,
fizzBuzzString,
fizzBuzzArray,
fizzBuzzMap,
};