Increment a number by one by manipulating the bits | C ++ 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 to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPosOfRightmostSetBit ( int n ) { return log2 ( n & - n ) ; } unsigned int toggleLastKBits ( unsigned int n , unsigned int k ) { unsigned int num = ( 1 << k ) - 1 ; return ( n ^ num ) ; } unsigned int incrementByOne ( unsigned int n ) { int k = getPosOfRightmostSetBit ( ~ n ) ; n = ( ( 1 << k ) n ) ; if ( k != 0 ) n = toggleLastKBits ( n , k ) ; return n ; } int main ( ) { unsigned int n = 15 ; cout << incrementByOne ( n ) ; return 0 ; }