Untitled
unknown
plain_text
a year ago
1.4 kB
1
Indexable
Never
import {last} from "lodash"; export function subtract(a: string, b: string) : string { const A = a.split(''); const B = b.split(''); const result = []; let carryOnNumber = 0; while (A.length > 0 || B.length > 0) { const lastDigitA = A.pop(); const lastDigitB = B.pop(); const subtraction = parseInt(lastDigitA ?? "0") - parseInt(lastDigitB ?? "0") - carryOnNumber; carryOnNumber = subtraction < 0 ? 1 : 0; if (subtraction == 0) { if (A.length > 0) { result.push(0); } else if (result.length == 0) { result.push(0); } } else { result.push( (10 + subtraction)%10 ); if (A.length == 0 && (B.length > 0 || carryOnNumber)) { // B > A and we need to show negative sign result.push("-"); } } } while (result.length > 1 && result.slice(-1)[0] == 0) { result.pop(); } return result.reverse().join(''); } const tests = [ ["123123123", "34342343"], ["100000", "0"], ["123", "123"], ["6", "6"], ["1000","1"], ["10000", "100"] ]; tests.forEach(x => { const correctAnswer = (parseInt(x[0]) - parseInt(x[1])).toString(); console.log(x, correctAnswer, subtract(x[0], x[1]), correctAnswer == subtract(x[0], x[1])) })