Iam_Sandeep

Count set bits count no of 1 bits bit mapping

Jun 13th, 2022
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. '''
  2. There are a lot of different ways to solve this problem, starting from transforming number to string and count number of ones. However there is a classical bit manipulation trick you should think about when you have bits problem.
  3.  
  4. If we have number n, then n&(n-1) will remove the rightmost in binary representation of n. For example if n = 10110100, then n & (n-1) = 10110100 & 10110011 = 10110000, where & means bitwize operation and. Very convinient, is it not? What we need to do now, just repeat this operation until we have n = 0 and count number of steps.
  5.  
  6. Complexity It is O(1) for sure, because we need to make no more than 32 operations here, but it is quite vague: all methods will be O(1), why this one is better than others? In fact it has complexity O(m), where m is number of 1-bits in our number. In average it will be 16 bits, so it is more like 16 operations, not 32 here, which gives us 2-times gain. Space complexity is O(1)
  7.  
  8. '''
  9. class Solution:
  10.     def hammingWeight(self, n):
  11.         ans = 0
  12.         while n:
  13.             n &= (n-1)
  14.             ans += 1
  15.         return ans
Advertisement
Add Comment
Please, Sign In to add comment