我在Java中尝试用carrys减法时遇到了一个问题。
public BigInt add(BigInt o) {
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
result[i] = (top + bot + carry) % 10;
carry = (top + bot + carry) / 10;
}
return new BigInt(trim(result));
}
public BigInt sub(BigInt o) {
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
carry = (top + bot + carry) / 10;
result[i] = (10 + top - bot - carry) % 10;
}
return new BigInt(trim(result));
}我不知道我做错了什么?我的加法类工作得很好,但减法给了我一个奇怪的答案。假设我减去5943-3952,得到2091。当我们知道答案是1991年。我所有的答案都是错误的,只有前两位数不正确。救命!
发布于 2017-01-11 19:26:45
你的代码有很多错误,但首先要做的就是让你得到想要的结果:
public BigInt sub(BigInt o)
{
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i)
{
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
int res = top - bot - carry;
result[i] = (10 + res) % 10;
carry = res < 0 ? 1 : 0;
}
return new BigInt(trim(result));
} 但是,请注意,您没有考虑到左操作数可能比右操作数小的事实,因此您将得到负结果。在将BigInt表示为“数字”数组时,似乎没有一种方法来表示负值。如果有的话,我看不出来。
如果你也有负值,有四种情况:
结果正-正:总是从最高值中减去最低值(总是38 - 17,而不是17 - 38),相应地调整符号(例如17 - 38 38 - 17 = 21,现在调整符号,因为第一个是最小的:
https://stackoverflow.com/questions/41540556
复制相似问题