Toggle all bits after most significant bit | CPP program to toggle set bits starting from MSB ; Function to toggle bits starting from MSB ; temporary variable to use XOR with one of a n ; Run loop until the only set bit in temp crosses MST of n . ; Toggle bit of n corresponding to current set bit in temp . ; Move set bit to next higher position . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void toggle ( int & n ) { int temp = 1 ; while ( temp <= n ) { n = n ^ temp ; temp = temp << 1 ; } } int main ( ) { int n = 10 ; toggle ( n ) ; cout << n ; return 0 ; }