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 ; required number ; Driver code
< ? php function getPosOfRightmostSetBit ( $ n ) { $ t = $ n & - $ n ; return log ( $ t , 2 ) ; } function toggleLastKBits ( $ n , $ k ) { $ num = ( 1 << $ k ) - 1 ; return ( $ n ^ $ num ) ; } function incrementByOne ( $ n ) { $ k = getPosOfRightmostSetBit ( ~ $ n ) ; $ n = ( ( 1 << $ k ) $ n ) ; if ( $ k != 0 ) $ n = toggleLastKBits ( $ n , $ k ) ; return $ n ; } $ n = 15 ; echo incrementByOne ( $ n ) ; ? >