当前位置:网站首页>338. Counting Bits

338. Counting Bits

2022-06-22 13:15:00 Sterben_ Da

338. Counting Bits

Easy

7064333Add to ListShare

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++)?

class Solution:
    def countBits(self, n: int) -> List[int]:
        """
        assert Solution().countBits(5) == [0, 1, 1, 2, 1, 2]
        assert Solution().countBits(2) == [0, 1, 1]
        
         Reference problem solving ideas : Dynamic programming and bit operation ,dp[i] representative i There are several binary systems 1,
         if i The end of the binary bit is 0, be dp[i]=dp[i>>1], Because the end is 0 了 ,1 The number of i The arithmetic shift right is the same 
         if i The end of the binary bit is 1, be dp[i]=dp[i-1]+1, Because the end is 1 了 , Is to make i-1 Binary bit of 1 Add one at the end of the present 1
         Time complexity :O(n), Spatial complexity :O(n)
        """

        dp = [0] * (n + 1)
        for i in range(1, n + 1):
            dp[i] = dp[i - 1] + 1 if i & 1 else dp[i >> 1]
        return dp

原网站

版权声明
本文为[Sterben_ Da]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221226254762.html