menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Data Science News

>

LeetCode M...
source image

Dev

3d

read

156

img
dot

Image Credit: Dev

LeetCode Meditations: Number of 1 Bits

  • Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
  • One way to count the set bits is by converting the number to a string or array and counting the 1s. However, a more efficient approach is to use bit manipulation.
  • By continuously performing the AND operation of n and (n - 1), we can remove the rightmost set bit and count each set bit as we go.
  • The time complexity of this approach is O(log n), and the space complexity is O(1).

Read Full Article

like

9 Likes

For uninterrupted reading, download the app