Number of 1 Bits Python
PROGRAM TO COUNT SET BITS IN AN INTEGER
OUTPUT:
2
BitsSetTable256 = [0] * 256# Function to initialise the lookup tabledef initialize(): # To initially generate the # table algorithmically BitsSetTable256[0] = 0 for i in range(256): BitsSetTable256[i] = (i & 1) + BitsSetTable256[i // 2]# Function to return the count# of set bits in ndef countSetBits(n): return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24])# Driver code# Initialise the lookup tableinitialize()n = 9print(countSetBits(n))
2
Comments
Post a Comment