Given any number n, and three operations on n:
I want to find the minimum n
To solve the above problem you can either use recursion or loops A recursive answer is already provided so i would try to give a while loop approach.
Logic: We should remember that the number multiple of 2 would always have less set bits than those which are not divisible by 2.
To solve your problem i'm using java code. I have tried it with few numbers and it works fine, if it doesn't add a comment or edit the answer
while(n!=1)
{
steps++;
if(n%2 == 0)
{
n=n/2;
}
else
{
if(Integer.bitCount(n-1) > Integer.bitCount(n+1))
{
n += 1;
}
else
{
n -=1;
}
}
}
System.out.println(steps);
The code is written in a very simple form so that it could be understood by everyone. Here n is the number entered and steps are the steps required to reach 1