diff --git a/lib/add-v16.js b/lib/add-v16.js new file mode 100644 index 0000000..40308b4 --- /dev/null +++ b/lib/add-v16.js @@ -0,0 +1,26 @@ +function add(firstNumber, secondNumber) { + const [shortNumber, longNumber] = + firstNumber.length < secondNumber.length + ? [firstNumber, secondNumber] + : [secondNumber, firstNumber]; + + let result = ''; + let lastSumLargeThanTen = false; + + for (let i = -1; i >= -shortNumber.length; i--) { + const sum = parseInt(shortNumber.at(i)) + parseInt(longNumber.at(i)); + + if (lastSumLargeThanTen) { + result = sum + parseInt(result.at(0)) + result.substring(1); + } else { + result = sum + result; + } + lastSumLargeThanTen = sum > 10; + } + + return ( + longNumber.substring(0, longNumber.length - shortNumber.length) + result + ); +} + +module.exports = add; diff --git a/lib/add.js b/lib/add.js index 1714b95..b69edd8 100644 --- a/lib/add.js +++ b/lib/add.js @@ -1,5 +1,28 @@ -function add() { - // 实现该函数 +function add(firstNumber, secondNumber) { + const [shortNumber, longNumber] = + firstNumber.length < secondNumber.length + ? [firstNumber, secondNumber] + : [secondNumber, firstNumber]; + + let result = ''; + let lastSumLargeThanTen = false; + + for (let i = shortNumber.length - 1; i >= 0; i--) { + const sum = + parseInt(shortNumber.substring(i, i + 1)) + + parseInt(longNumber.substring(i, i + 1)); + + if (lastSumLargeThanTen) { + result = sum + parseInt(result.substring(0, 1)) + result.substring(1); + } else { + result = sum + result; + } + lastSumLargeThanTen = sum > 10; + } + + return ( + longNumber.substring(0, longNumber.length - shortNumber.length) + result + ); } -module.exports = add \ No newline at end of file +module.exports = add; diff --git a/test/test.spec.js b/test/test.spec.js index 935b70e..ccdf10f 100644 --- a/test/test.spec.js +++ b/test/test.spec.js @@ -1,11 +1,14 @@ var add = require('../lib/add') +// var add = require('../lib/add-v16'); describe('大数相加add方法', function () { test('字符串"42329"加上字符串"21532"等于"63861"', function () { expect(add('42329', '21532')).toBe('63861') }) - + test('"843529812342341234"加上"236124361425345435"等于"1079654173767686669"', function () { - expect(add('843529812342341234', '236124361425345435')).toBe('1079654173767686669') + expect(add('843529812342341234', '236124361425345435')).toBe( + '1079654173767686669' + ) }) -}) \ No newline at end of file +})