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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay