개발이 취미인 주니어 기획자

[DP][JavaScript][LeetCode] #338. Counting Bits 본문

문제 풀이/알고리즘 문제 풀이

[DP][JavaScript][LeetCode] #338. Counting Bits

큐 2023. 5. 1. 18:01
728x90
반응형

#Dynamic Programming(DP)  #EASY

 

Counting Bits - LeetCode

Can you solve this real interview question? Counting Bits - Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.   Example 1: Input: n = 2 Output: [0,1,1

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Counting Bits
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

🎃 제한 사항
0 <= n <= 10^5

입출력 예

nums result
2 [0, 1, 1]
5 [0, 1, 1, 2, 1, 2]

 

🌷 내 코드

var countBits = function (n) {
  let dp = [0];
  let offset = 1;

  for (let i = 1; i <= n; i++) {
    if (offset * 2 === i) {
      offset = i;
    }
    dp[i] = 1 + dp[i - offset];
  }
  return dp;
};

 

🌷 코멘트

DP가 그렇게 많이 나온다길래 제일 기본형을 한번 해보았다 
하나하나 다 써서 패턴을 찾아야되는데 그게 좀 어려웠음

 


블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!

~대가리 꽃밭인 디지털 노마드가 꿈이예요~

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

noob. qminlee723 has 8 repositories available. Follow their code on GitHub.

github.com

728x90
반응형