我有这个代码:
public static int rsnpeasant(int x, int y) {
if ((y & 1) == 0) {
y = y / 2;
x = x * 2;
rsnpeasant(x, y);
} else {
sum = sum + x;
y = y / 2;
y = y - 1 / 2;
x = x * 2;
if (y == 1) {
sum = total;
return total;
} else {
rsnpeasant(x, y);
}
}
total = sum;
return total;
}
错误发生在第一个 if
语句中的第一个 rsnpeasant(x,y);
行。它似乎永远循环到该行,即使如果 y
是奇数,它应该转到 else
语句。如果y
除以2
,它在某个时刻应该变成奇数。
Link我正在尝试编写代码
最佳答案
y=y-1/2
...
运算顺序将计算 1/2
并从 y
中减去它。在整数算术中,1/2
是 0。我认为您需要 y=(y-1)/2
。
关于java - 当输入偶数时尝试重复该方法时出现堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40476411/