Get the App
SLTechnology News&Howtos  ›  Development  › 

How does python calculate how many 1s are in the binary number of a number

Shulou Source: shulou.com Published: 2022-06-01 04:49:25 10月03日 Update

This article is about how python calculates how many ones are in the binary number of a number. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Calculate how many 1s are in the binary number of a number

I believe that with the previous foundation, it is easy to implement this algorithm. Simply through the bit operation, and operation with 1 to see if the result is 1, and then move 1 bit to the right to continue to judge. The Python code is implemented as follows:

Def number1Bit (x): count = 0 while x: count = count + (xan1) x = x > > 1 return count

There is a problem with this, that is, if there are consecutive zeros, then multiple shifts need to be done. Is there an easy way to skip consecutive zeros?

That is to do the & operation with (xMel 1). It may not be easy to understand here. Give me an example.

X 1110 0000x-1 1101 1111x & (x Mel 1) 1100 0000

In this way, the last one will be detected.

The Python code is implemented as follows:

Def number1Bit (x): count = 0 while x: count = count + 1 x = x & (x Mel 1) return count Thank you for reading! This is the end of the article on "how python calculates the number of 1s in a binary number". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Tags: Binary numerical value operation code content multiple that is way more article good practical basic situation article look knowledge algorithm result problem Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft Xiaomi NVidia macOS