프로그래밍/코딩테스트

[LeetCode] 338. Counting Bits / Swift

turu 2021. 6. 26. 23:27

[문제 보기]

더보기

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] Explanation: 0 --> 0 1 --> 1 2 --> 10

Example 2:

Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101

 

Constraints:

  • 0 <= n <= 105

 

Follow up:

  • It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?
  • Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?

 

https://leetcode.com/problems/counting-bits/

 

Counting Bits - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 


다이나믹 프로그래밍을 이용하는 문제였다.

이진수 1011의 1의 갯수를 구한다고 하면,

(f: 입력받은 숫자의 1의 갯수)

가장 앞자리부터 마지막 자리 전까지의 1의 갯수(101) + 가장 마지막 자리의 1의 갯수(1) = 2 + 1 = 3으로 분할하여 구할 수 있다.

이것을 수식으로 표현하면 f(1011) = f(101) + f(1)이다.

가장 앞자리부터 마지막 자리 전까지의 숫자를 구하는 방법은 shift연산으로 구할 수 있고, 가장 마지막 자리의 숫자는 i&1으로 구할 수 있다. 

다이나믹 프로그래밍 기법을 이용해서 이 부분은 문제에서 요구하는 o(n)으로 구할 수 있다.

dp배열을 사용하는 피보나치 수열 구하는 문제와 비슷하지만 비트연산자도 함께 생각해야 해서 어려웠다.

 

 

class Solution {
    func countBits(_ n: Int) -> [Int] {
        var ans = [Int](repeating: 0, count: n+1)
        ans[0] = 0
        if n > 0 {
            ans[1] = 1
        }
        

        for i in (0...n) {
            ans[i] = ans[i>>1] + ans[i&1]
        }
        
        return ans
    }
}
반응형