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
< ? php function find_leftmost_unsetbit ( $ n ) { $ ind = -1 ; $ i = 1 ; while ( $ n ) { if ( ! ( $ n & 1 ) ) $ ind = $ i ; $ i ++ ; $ n >>= 1 ; } return $ ind ; } function perform_steps ( $ n ) { $ left = find_leftmost_unsetbit ( $ n ) ; if ( $ left == -1 ) { echo " No ▁ steps ▁ required " ; return ; } $ step = 1 ; while ( find_leftmost_unsetbit ( $ n ) != -1 ) { if ( $ step % 2 == 0 ) { $ n += 1 ; echo " Step " , $ step , " : ▁ Increase ▁ by ▁ 1 STRNEWLINE " ; } else { $ m = find_leftmost_unsetbit ( $ n ) ; $ num = pow ( 2 , $ m ) - 1 ; $ n = $ n ^ $ num ; echo " Step " , $ step , " : ▁ Xor ▁ with ▁ " , $ num , " STRNEWLINE " ; } $ step += 1 ; } } $ n = 39 ; perform_steps ( $ n ) ; ? >