- Published on
CodeWars: 6kyu – Counting Bits
You got numbers, you want to know how many bits are flipped to a 1
Well, first we need to convert our number from an integer to a binary number.
There are two ways to do this:
Variant 1: String Formatting
Variant 2: Build In a binary converter "bin(number)"
Then well now we just have to count the occurrences of ones.
def count_bits: return bin(number).count(str(1))
Note: It is important to count the instances of ones as strings of "1" instead of integers of 1. This is the case because we converted the int to a string and are now looking for strings instead of numbers.