Java 对于最少的移动次数,我们需要最大限度地增加翻倍的次数
如果你从1美元开始,并且每次移动,你可以加倍你的钱或者再增加1美元,那么你要达到n的最小移动次数是多少$ 我写了一些代码,但看起来它在结束之前就停止了。我想我需要另一个循环,但找不到解决方案。有人能帮我调整代码吗?如果可能的话,我不想要复杂的代码Java 对于最少的移动次数,我们需要最大限度地增加翻倍的次数,java,Java,如果你从1美元开始,并且每次移动,你可以加倍你的钱或者再增加1美元,那么你要达到n的最小移动次数是多少$ 我写了一些代码,但看起来它在结束之前就停止了。我想我需要另一个循环,但找不到解决方案。有人能帮我调整代码吗?如果可能的话,我不想要复杂的代码 public class NumberOfMoves { public static void main(String[] args) { int n$ = 200; //target number of bucks
public class NumberOfMoves {
public static void main(String[] args) {
int n$ = 200; //target number of bucks
int steps = 0;
for (int i = 0; i < n$; i++) {
if (n$ % 2 == 0) { //if 200/2 equals even number than n$/2== this number
n$ = n$ / 2;
steps++;
// System.out.println(n$);
} else {
n$ = n$ - 1;
steps++;
} // end else
}// end loop
System.out.println("Steps " + steps);
} //end main
} //end class
公共类NumberOfMoves{
公共静态void main(字符串[]args){
int n$=200;//目标美元数
int步数=0;
对于(int i=0;i
您不知道什么时候应该退出for
循环。您正在减少n$
,并且似乎应该在n$
为1时立即停止。那么i
在做什么呢?它正在计数,并将在n$
达到1之前的某个点达到n$
。我认为循环应该是,而(n$>1)
你可以用while代替for,我不明白你为什么要用
I
和for循环。为什么不在(n>1)时执行?你不是从什么开始的吗?非常感谢!这就是我需要的。我想你的意思是,而(n$>1)
?OP说他们从$1if(n$>1)开始,然后它将停止在2,因此计数将减少1,其(n$>0)不,它将继续运行直到它为1,然后条件将为false,因此它将退出。如果使用n$>0
,则对于$n==1
,您将在它应该为零时返回1步。
package sample;
class Main1
{
public static void main(String[] args) {
int n$ = 200; //target number of bucks
int steps = 0;
while (n$>1) {
if (n$ % 2 == 0) { //if 200/2 equals even number than n$/2== this number
n$ = n$ / 2;
steps++;
// System.out.println(n$);
} else {
n$ = n$ - 1;
steps++;
} // end else
}// end loop
System.out.println("Steps " + steps);
} //end main
} //end class}