Increment a number by one by manipulating the bits | Java 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 java . io . * ; import java . util . * ; class GFG { static int getPosOfRightmostSetBit ( int n ) { return ( int ) ( Math . log ( n & - n ) / Math . log ( 2 ) ) ; } static int toggleLastKBits ( int n , int k ) { int num = ( 1 << k ) - 1 ; return ( n ^ num ) ; } static int incrementByOne ( int n ) { int k = getPosOfRightmostSetBit ( ~ n ) ; n = ( ( 1 << k ) n ) ; if ( k != 0 ) n = toggleLastKBits ( n , k ) ; return n ; } public static void main ( String [ ] args ) { int n = 15 ; System . out . println ( incrementByOne ( n ) ) ; } }