Increment a number by one by manipulating the bits | python 3 implementation to increment a number by one by manipulating the bits ; function to find the position of rightmost set bit ; function to toggle the last m bits ; calculating a number ' num ' having ' m ' bits and all are set ; toggle the last m bits and return the number ; function to increment a number by one by manipulating the bits ; get position of rightmost unset bit if all bits of ' n ' are set , then the bit left to the MSB is the rightmost unset bit ; kth bit of n is being set by this operation ; from the right toggle all the bits before the k - th bit ; required number ; Driver program
import math NEW_LINE def getPosOfRightmostSetBit ( n ) : NEW_LINE INDENT return math . log2 ( n & - n ) NEW_LINE DEDENT def toggleLastKBits ( n , k ) : NEW_LINE INDENT num = ( 1 << ( int ) ( k ) ) - 1 NEW_LINE return ( n ^ num ) NEW_LINE DEDENT def incrementByOne ( n ) : NEW_LINE INDENT k = getPosOfRightmostSetBit ( ~ n ) NEW_LINE n = ( ( 1 << ( int ) ( k ) ) n ) NEW_LINE if ( k != 0 ) : NEW_LINE INDENT n = toggleLastKBits ( n , k ) NEW_LINE DEDENT return n NEW_LINE DEDENT n = 15 NEW_LINE print ( incrementByOne ( n ) ) NEW_LINE