human
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"
Solution in Python:
assistant
#Here is code to reduce a number to 1 by performing given operations and the other steps required.
 def set_bits ( n ) :
	count = 0
	while ( n ) :
		count += n % 2
		n //= 2
	return count
def minSteps ( n ) :
	ans = 0
	while ( n != 1 ) :
		if ( n % 2 == 0 ) :
			n //= 2
		elif ( n == 3 or set_bits ( n - 1 ) < set_bits ( n + 1 ) ) :
			n -= 1
		else :
			n += 1
		ans += 1
	return ans
n = 15
print ( minSteps ( n ) )