Print steps to make a number in form of 2 ^ X | C ++ program to implement the above approach ; Function to find the leftmost unset bit in a number . ; Function that perform the step ; Find the leftmost unset bit ; If the number has no bit unset , it means it is in form 2 ^ x - 1 ; Count the steps ; Iterate till number is of form 2 ^ x - 1 ; At even step increase by 1 ; Odd step xor with any 2 ^ m - 1 ; Find the leftmost unset bit ; 2 ^ m - 1 ; Perform the step ; Increase the steps ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_leftmost_unsetbit ( int n ) { int ind = -1 ; int i = 1 ; while ( n ) { if ( ! ( n & 1 ) ) ind = i ; i ++ ; n >>= 1 ; } return ind ; } void perform_steps ( int n ) { int left = find_leftmost_unsetbit ( n ) ; if ( left == -1 ) { cout << " No ▁ steps ▁ required " ; return ; } int step = 1 ; while ( find_leftmost_unsetbit ( n ) != -1 ) { if ( step % 2 == 0 ) { n += 1 ; cout << " Step " << step << " : ▁ Increase ▁ by ▁ 1 STRNEWLINE " ; } else { int m = find_leftmost_unsetbit ( n ) ; int num = pow ( 2 , m ) - 1 ; n = n ^ num ; cout << " Step " << step << " : ▁ Xor ▁ with ▁ " << num << endl ; } step += 1 ; } } int main ( ) { int n = 39 ; perform_steps ( n ) ; return 0 ; }