Count unset bits of a number | An optimized Python program to count unset bits in an integer . ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Count set bits in toggled number ; Driver code
import math NEW_LINE def countUnsetBits ( n ) : NEW_LINE INDENT x = n NEW_LINE n |= n >> 1 NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE t = math . log ( x ^ n , 2 ) NEW_LINE return math . floor ( t ) NEW_LINE DEDENT n = 17 NEW_LINE print ( countUnsetBits ( n ) ) NEW_LINE