Skip to content

Commit 6524b14

Browse files
committed
add: solve DaleStudy#233 Counting Bits with ts
1 parent 6d2167b commit 6524b14

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

β€Žcounting-bits/Yjason-K.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* 각 수의 λΉ„νŠΈμ˜ 개수λ₯Ό κ³„μ‚°ν•˜λŠ” ν•¨μˆ˜
3+
* @param {number} nums - μ΅œλŒ€ 수
4+
* @returns {number[]} - 각 수의 λΉ„νŠΈμ˜ 개수 λ°°μ—΄
5+
*
6+
* μ‹œκ°„ λ³΅μž‘λ„: O(n)
7+
* - nums 만큼 λ°˜λ³΅ν•˜λ©°, 각 수의 λΉ„νŠΈμ˜ 개수λ₯Ό 계산
8+
*
9+
* 곡간 λ³΅μž‘λ„: O(n)
10+
* - dp 배열을 μ‚¬μš©ν•˜μ—¬ O(n) 만큼 μΆ”κ°€ 곡간이 ν•„μš”
11+
*/
12+
function countBits(nums: number): number[] {
13+
// dp 배열을 μƒμ„±ν•˜κ³ , λͺ¨λ‘ 0으둜 μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.
14+
const dp: number[] = new Array(nums + 1).fill(0);
15+
16+
// 각 μˆ˜μ— λŒ€ν•΄, λΉ„νŠΈμ˜ 개수λ₯Ό κ³„μ‚°ν•©λ‹ˆλ‹€.
17+
for (let num = 1; num <= nums; num++) {
18+
// num을 2μ§„μˆ˜λ‘œ ν‘œν˜„ν–ˆμ„ λ•Œ, 1의 κ°œμˆ˜λŠ” 2μ§„μˆ˜λ‘œ λ³€ν™˜ν•˜μ—¬ λ¬Έμžμ—΄λ‘œ λ³€ν™˜ ν›„,
19+
// '1'이 ν¬ν•¨λœ λ¬Έμžμ—΄μ˜ 길이λ₯Ό κ³„μ‚°ν•©λ‹ˆλ‹€.
20+
dp[num] = dp[Math.floor(num / 2)] + (num % 2);
21+
}
22+
23+
return dp;
24+
}
25+

0 commit comments

Comments
Β (0)