Fix zero subtraction
All checks were successful
timw4mail/rusty-numbers/pipeline/head This commit looks good

This commit is contained in:
Timothy Warren 2020-03-11 14:01:45 -04:00
parent a5b727a156
commit 74744095f1

View File

@ -175,15 +175,9 @@ impl Sub for BigInt {
let a = *self.inner.get(i).unwrap_or(&0usize); let a = *self.inner.get(i).unwrap_or(&0usize);
let b = *rhs.inner.get(i).unwrap_or(&0usize); let b = *rhs.inner.get(i).unwrap_or(&0usize);
if a > 0 && (a - borrow) >= b { if a >= borrow && (a - borrow) >= b {
let res = a - b - borrow; let res = a - b - borrow;
// Don't add an extra zero if you borrowed everything
// from the most significant digit
if res == 0 && digits > 0 && i == digits -1 {
return out;
}
out.inner.push(res); out.inner.push(res);
borrow = 0; borrow = 0;
} else { } else {
@ -462,9 +456,9 @@ mod tests {
let a = BigInt::new(); let a = BigInt::new();
let b = BigInt::new(); let b = BigInt::new();
// let c = a.clone() - b.clone(); let c = a.clone() - b.clone();
// assert_eq!(a.clone(), b.clone()); assert_eq!(a.clone(), b.clone());
// assert_eq!(c, a.clone()); assert_eq!(c, a.clone());
let c = a.clone() + b.clone(); let c = a.clone() + b.clone();
assert_eq!(a.clone(), b.clone()); assert_eq!(a.clone(), b.clone());