Finding the total number of set-bits from 1 to n

后端 未结 16 2070
轻奢々
轻奢々 2020-12-04 09:54

Write an algorithm to find F(n) the number of bits set to 1, in all numbers from 1 to n for any given value of n.

Complexity should be O(log n)

16条回答
  •  渐次进展
    2020-12-04 10:16

    This question can be solved using DP with Bitmasking.

    The basic intuition behind bottom-up approach is that we are going to directly access number of set bits in the number having value current_number/2 and we are also going to check whether last bit is set in this current_number or not by just doing and operation with 1.

    current_number/2 or current_number>>1 basically removes the last bit of this current_number so to include that bit in our count we have to manually check the last bit of this number using & operation.

    This would be expression for computing number of set bits in a number i dp[i]=dp[i>>1]+(i&1)

    If you still get stuck while solving this question then you can refer to the following video for a better explanation:-

    Video Link: https://youtu.be/fCvfud4p6No

提交回复
热议问题