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
def set_bits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n % 2 NEW_LINE n //= 2 NEW_LINE DEDENT return count NEW_LINE DEDENT def minSteps ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( n != 1 ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT n //= 2 NEW_LINE DEDENT elif ( n == 3 or set_bits ( n - 1 ) < set_bits ( n + 1 ) ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT n += 1 NEW_LINE DEDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 15 NEW_LINE print ( minSteps ( n ) ) NEW_LINE