DEV Community

Bernice Waweru
Bernice Waweru

Posted on

2 1

Number of 1 Bits

Instructions

Approach

There are several ways to solve this problem. Let's look at a few.

Using count()

We convert the decimal number to binary, replace "0b" with no value and count the number of 1's

Implementation

def hammingWeight(self, n: int) -> int:
        bits =  bin(n).replace("0b", "")
        return bits.count('1')

Enter fullscreen mode Exit fullscreen mode

Using the bit_count() method

The method returns the number of ones in the binary representation of the absolute value of the integer.

def hammingWeight(self, n: int) -> int:
        return n.bit_count()
Enter fullscreen mode Exit fullscreen mode

You can review this resource for a better understanding of the method.

Bit Manipulation

We can loop through the number and count the number of 1's
Using the modulus operator(%) we can get the number of 1's and shift n to the right until all 32bits are zeros.

  • n%2 will return 0 or 1 so the count only changes when it is a 1.

Implementation

def hammingWeight(self, n: int) -> int:
        count = 0
        while n:
            count += n%2
            n = n >> 1
        return count
Enter fullscreen mode Exit fullscreen mode

This algorithm has a constant time complexity O(1) because we iterate through 32 bits.
The space complexity is O(1) because we do not need extra memory.

I hope you found this helpful. Let me know of other solution approaches.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay