Print steps to make a number in form of 2 ^ X | 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
function find_leftmost_unsetbit ( n ) { let ind = - 1 ; let i = 1 ; while ( n ) { if ( ! ( n & 1 ) ) ind = i ; i ++ ; n >>= 1 ; } return ind ; } function perform_steps ( n ) { let left = find_leftmost_unsetbit ( n ) ; if ( left == - 1 ) { document . write ( " " ) ; return ; } let step = 1 ; while ( find_leftmost_unsetbit ( n ) != - 1 ) { if ( step % 2 == 0 ) { n += 1 ; document . write ( " " + step + " " ) ; } else { let m = find_leftmost_unsetbit ( n ) ; let num = Math . pow ( 2 , m ) - 1 ; n = n ^ num ; document . write ( " " + step + " " + num + " " ) ; } step += 1 ; } } let n = 39 ; perform_steps ( n ) ;