从0走到x点,每次可以前进一格,退后一格,或者翻倍
即 n = n+1;
n= n-1;
n = n*2;
输入: 位置x
返回:最少的走动次数
我用的是递归来求解的,代码如下:
public class ZhaoHang2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();//个数
int count = 0;
count = getCount(x,count);
}
public static int getCount(int x,int count){
if(x>=2){
while((x & 0x1) == 0){
x = x>>1;
count++;
}
System.out.println(x+","+count);
}
if(x==1)
return count+1;
return Math.min(getCount(x+1, count+1), getCount(x-1, count+1));
}
}