minimum number of steps to reduce number to 1

后端 未结 6 2021
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 12:53

Given any number n, and three operations on n:

  1. add 1
  2. subtract 1
  3. divide by 2 if the number is even

I want to find the minimum n

6条回答
  •  眼角桃花
    2020-12-07 13:21

    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

提交回复
热议问题