Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

提交作业二,计算大数相加 #257

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
name: github-actions
on: [push]
jobs:
check-bats-version:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '14'
- run: npm install -g bats
- run: bats -v
38 changes: 37 additions & 1 deletion lib/add.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,41 @@
function add() {
function add(a, b) {
// 实现该函数
// 非数字报错
if(isNaN(a) || isNaN(b)) throw Error('需要传入数字或字符串型数字')
const maxLength = 16
// 边界:16位以内可以正常相加
if(String(a).length<maxLength && String(b).length<maxLength) {
return String(Number(a) + Number(b))
}

// 以10位数作一个阈值进行分割
const aList = a.match(/\d{1,10}/g)
const bList = b.match(/\d{1,10}/g)

// 两数的最大长度作为结果数组的长度,+1一个长度防止满十进一
let resultLength = Math.max(aList.length, bList.length)
let addResultList = Array(resultLength+1).fill('')
let aLength = aList.length - 1
let bLength = bList.length - 1
// 从尾部开始计算,两两相加后把结果加到结果数组上
// 如果两数相加长度大于a/b的最大长度,说明是首位满十,往结果数组的前一位进一
while(aLength>=0 || bLength>=0) {
const resultTemp = Number(aList[aLength] || 0) + Number(bList[bLength] || 0)
// 判断长度是否溢出
if(resultTemp.length > Math.max(aList[aLength].length, bList[bLength].length)) {
addResultList[resultLength - 1] = 1
resultTemp = resultTemp.slice(1)
}
addResultList[resultLength] = addResultList[resultLength] + resultTemp

aLength--
bLength--
resultLength--
}

const result = addResultList.join('')

return result
}

module.exports = add
4 changes: 3 additions & 1 deletion test/test.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ describe('大数相加add方法', function () {
test('"843529812342341234"加上"236124361425345435"等于"1079654173767686669"', function () {
expect(add('843529812342341234', '236124361425345435')).toBe('1079654173767686669')
})
})
})

// test: add git actions