minimum number of steps to reduce number to 1

后端 未结 6 2019
爱一瞬间的悲伤
爱一瞬间的悲伤 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:28

    I am really bad at binaries so not counting the lsb or msb. What about below program -

    public class ReduceNto1 {
        public static void main(String[] args) {
            int count1 = count(59);//input number
            System.out.println("total min steps - " + count1);
        }
        static int count(int n){
            System.out.println(n + " > ");
            if(n==1){
                return 0;
            }
            else if(n %2 ==0){
    
                return 1 + count(n/2);
            }else{
                return 1 + Math.min(count(n-1), count(n+1));
            }
        }
    }

提交回复
热议问题