python algorithm design - binary

Python algorithm design source code: https://github.com/MakerChen66/Python3Algorithm

Copyright statement: Originality is not easy, this article prohibits plagiarism, reprinting, infringement must be investigated!

1. The number of binary 1s

When you write down the binary form of a positive integer, do you want to find out how many bits are 1 in this binary number?

For example: 199 = 0b11000111

An obvious solution is to get a unit mask, iterate over the binary number X & (1 << k) and return a non-zero result, this way the bits of 0's are compared with the bits of 1's All counted

Is there a better way to count only 1 bits and completely ignore 0 bits? You can have more ideas of your own, but we don't need them now

Python algorithm implementation:

def count_1bits(value):
    counts = 0
    while value:
        value &= value - 1
        counts += 1
    print(counts)
count_1bits(0b11000111)

Output result:
insert image description here
Note : 0b11000111 is realized by the function bin() in Python, as shown in the figure below:
insert image description here

2. Source code download

Python algorithm design source code download:

3. Author Info

Author: Xiaohong's Fishing Daily, Goal: Make programming more interesting!

Original WeChat public account: " Xiaohong Xingkong Technology ", focusing on algorithms, crawlers, websites, game development, data analysis, natural language processing, AI, etc., looking forward to your attention, let us grow and code together!

Copyright Note: This article prohibits plagiarism and reprinting, and infringement must be investigated!

Supongo que te gusta

Origin blog.csdn.net/qq_44000141/article/details/121914248
Recomendado
Clasificación