python - count number of ones in a given integer -


How do you calculate the number of people in the binary representation of the given integer.

Say you have given a number, 20 , which is in binary, 10100 , so many people have 2 numbers.

Use the awesome module.

  & gt; & Gt; & Gt; Counter import from & gt; & Gt; & Gt; Binary = Bin (20) [2:]> gt; & Gt; & Gt; Counter (binary) counter ({'0': 3, '1': 2})   

Or you can use the built-in function count () :

  & gt; & Gt; & Gt; Binary = Bin (20) [2:]> gt; & Gt; & Gt; BinaryCount ('1') 2   

Or even:

  & gt; & Gt; & Gt; (Amount for bin (20) in (I): If I == '1' 2)   

But this final solution is slower than count (< / Code>

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -