以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!
BFE.devAI解答 - JavaScript 代码题
75. 实现大整数减法(BigInt)
思路:
- 由于输入字符串可能很长,需要使用数组表示。
- 从最高位开始,逐位相减,判断是否需要借位。
- 所有位数计算完后,需要去除前导零。
实现代码如下:
function subtract(a, b) { const lenA = a.length, lenB = b.length; const arrA = Array.from(a, Number); const arrB = Array.from(b, Number); const result = []; // 补齐位数 while (arrA.length > arrB.length) arrB.unshift(0); while (arrB.length > arrA.length) arrA.unshift(0); let borrow = 0; for (let i = lenA - 1; i >= 0; i--) { let n = arrA[i] - arrB[i] - borrow; if (n < 0) { n += 10; borrow = 1; } else { borrow = 0; } result.unshift(n); } // 去除前导零 while (result.length > 1 && result[0] === 0) result.shift(); return result.join('');}
测试:
console.log(subtract('1000000000000000000000', '999999999999999999999')); // '1'console.log(subtract('100', '5')); // '95'console.log(subtract('111', '99')); // '12'
时间复杂度:O(n),其中 n 为数的位数。