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!
Table of contents
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:
Note : 0b11000111 is realized by the function bin() in Python, as shown in the figure below:
2. Source code download
Python algorithm design source code download:
- GitHub download link: Portal
- Link to the original text: Read the original text
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!