|
| 1 | +/** |
| 2 | + * @param {number} n |
| 3 | + * @return {number[]} |
| 4 | + */ |
| 5 | + |
| 6 | +/** |
| 7 | + * Runtime: 82ms, Memory: 57.03MB |
| 8 | + * |
| 9 | + * Time complexity: O(logN < N+1 ? N+1 : logN ๋จ,๋ณดํต์ ๊ฒฝ์ฐ N+1) |
| 10 | + * Space complexity: O(N+1) |
| 11 | + * |
| 12 | + * Note: necessary to think of an alternative approach |
| 13 | + * **/ |
| 14 | + |
| 15 | +function decimalToBinary(decimal) { |
| 16 | + let binaryBitCount = 0; |
| 17 | + |
| 18 | + while (decimal > 1) { |
| 19 | + binaryBitCount += decimal % 2 === 1 ? 1 : 0; |
| 20 | + decimal = Math.floor(decimal / 2); |
| 21 | + } |
| 22 | + binaryBitCount += decimal === 1 ? 1 : 0; |
| 23 | + |
| 24 | + return binaryBitCount; |
| 25 | +} |
| 26 | +var countBits = function (n) { |
| 27 | + const answer = []; |
| 28 | + |
| 29 | + for (let i = 0; i < n + 1; i++) { |
| 30 | + answer.push(decimalToBinary(i)); |
| 31 | + } |
| 32 | + |
| 33 | + return answer; |
| 34 | +}; |
| 35 | + |
| 36 | +/** |
| 37 | + * ์ธ์ ๊น์๋ ํ์ด |
| 38 | + * |
| 39 | + * Runtime : 60ms |
| 40 | + * |
| 41 | + * ๋นํธ ์ฐ์ฐ์ ์์ฑ๊ณผ dp๋ฅผ ํ์ฉํด ํผ ํ์ด |
| 42 | + * |
| 43 | + * [๊ฐ๋จ์ค๋ช
] |
| 44 | + * 4์ผ๋ 100์ด๊ณ , 5์ผ๋ 101, 6์ผ๋ 110์ด๋ค. |
| 45 | + * ์ด๋ 4๋ฅผ 2์ง์๋ก ํํํ 100์ด ๊ฐ์ง 1์ ๊ฐ์๋ฅผ ํ์ฉํด 5,6์ 1์ ๊ฐ์๋ฅผ ์ฐพ๋ ๊ฒ์ด๋ค. |
| 46 | + * 100์์ 1์ ๋ํ 101์ด๋, 110์ 100์ 1์ ๊ฐ์์ธ 1๊ฐ์์ 1์ ๋ํ 2๊ฐ๊ฐ ๋๋ค. |
| 47 | + * result[5 & 4] => ๋นํธ ์ฐ์ฐ์ ํตํด 100๊ณผ 101์ ๋นํธ ์ค๋ ์ฐ์ฐ์ ํด์ 100์ด ๋๊ณ , ์ด๋ 101์ ๊ฐ์ฅ ์ค๋ฅธ์ชฝ 1์ ์ ๊ฑฐํ ๊ฐ์ด ๋๋ค. |
| 48 | + * result[6 & 5] => ๋นํธ ์ฐ์ฐ์ ํตํด 110๊ณผ 101์ ๋นํธ ์ค๋ ์ฐ์ฐ์ ํด์ 100์ด ๋๊ณ , ์ด๋ 110์ ๊ฐ์ฅ ์ค๋ฅธ์ชฝ 1์ ์ ๊ฑฐํ ๊ฐ์ด ๋๋ค. |
| 49 | + * ์ด์ง์๋ 1์ฉ ๋ํ๊ธฐ ๋๋ฌธ์ ๋๋ณด๋ค ํ๋ ํฐ ์์ ์ค๋ ์ฐ์ฐ์ ํ๋ฉด ์์ ์๊ฐ 0์ผ๋ก ๋๋๋ฉด ํฐ ์๋ 1๋ก ๋๋๊ณ , |
| 50 | + * ์์ ์๊ฐ 1๋ก ๋๋๋ฉด ํฐ ์๋ 0์ผ๋ก ๋๋๊ธฐ ๋๋ฌธ์ ์ด๋ฐ ์์ฑ์ ๊ฐ๋๋ค. |
| 51 | + * |
| 52 | + * |
| 53 | + */ |
| 54 | + |
| 55 | +var countBits = function (n) { |
| 56 | + let result = new Array(n + 1).fill(0); |
| 57 | + for (let i = 1; i <= n; i++) { |
| 58 | + result[i] = result[i & (i - 1)] + 1; |
| 59 | + } |
| 60 | + return result; |
| 61 | +}; |
0 commit comments