Reduce a number to 1 by performing given operations | Set 2 | Function to return the number of set bits in n ; Function to return the minimum steps required to reach 1 ; If n is even then divide it by 2 ; If n is 3 or the number of set bits in ( n - 1 ) is less than the number of set bits in ( n + 1 ) ; Increment the number of steps ; Return the minimum number of steps ; Driver code
function set_bits ( n ) { let count = 0 ; while ( n ) { count += n % 2 ; n = parseInt ( n / 2 ) ; } return count ; } function minSteps ( n ) { let ans = 0 ; while ( n != 1 ) { if ( n % 2 == 0 ) n = parseInt ( n / 2 ) ; else if ( n == 3 || set_bits ( n - 1 ) < set_bits ( n + 1 ) ) n -- ; else n ++ ; ans ++ ; } return ans ; } let n = 15 ; document . write ( minSteps ( n ) ) ;