In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.