Find most significant set bit of a number | Python program to find MSB number for given n . ; Suppose n is 273 ( binary is 100010001 ) . It does following 100010001 | 010001000 = 110011001 ; This makes sure 4 bits ( From MSB and including MSB ) are set . It does following 110011001 | 001100110 = 111111111 ; Increment n by 1 so that there is only one set bit which is just before original MSB . n now becomes 1000000000 ; Return original MSB after shifting . n now becomes 100000000 ; Driver code
def setBitNumber ( n ) : NEW_LINE INDENT 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 n = n + 1 NEW_LINE return ( n >> 1 ) NEW_LINE DEDENT n = 273 NEW_LINE print ( setBitNumber ( n ) ) NEW_LINE