Ich habe ein Problem versucht, mit Carrys in Java zu subtrahieren.BigInt Subtraktion
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));
}
Ich weiß nicht, was ich falsch mache? Meine Additionsklasse funktioniert perfekt, aber Subtraktion gibt mir eine seltsame Antwort. Nehmen wir an, ich subtrahiere 5943-3952 und bekomme 2091. Wenn wir wissen, ist die Antwort 1991. Alle meine Antworten sind nur in den ersten beiden Ziffern falsch. Hilfe!!!!
https://ericlippert.com/2014/03/05/how-to-debug-small-programme / – shmosel