-
Notifications
You must be signed in to change notification settings - Fork 292
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
大数相加网上找的一个很简洁的案例,个人觉得写得很好 #111
Comments
这个是最简洁的 |
添加注释,方便理解: function sumStrings(a,b){
var res = '', // 存储最终结果
c = 0; // 假设想加结果>=10,那么把10位缓存起来
// 将字符串切割成数组,每一位单独相加
a = a.split('')
b = b.split('')
// 不断循环相加,直到所有数字都加完为止
while (a.length || b.length || c) {
/*
一、c为Boolean:
1. true与数字n相加,相当于1+n
2. false与数字n相加,相当于0+n
二、[Bitwise NOT (~)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT)
1. 数字进行~~运算,例如~~3的结果为3
2. a和b两个数组长度可能不一致,其中一个会先清空
3. 假设a为[],a.pop()为undefined
4. ~~undefined的结果为0
三、c += ~~a.pop() + ~~b.pop() 可以计算出每一位相加的结果
*/
c += ~~a.pop() + ~~b.pop()
/*
1. c的结果可能>=10,但每一位只能存储0-9的数字,因此要用c % 10取个位数
2. 每位数要存储在结果的首尾
*/
res = (c % 10) + res
/*
判断c是否>=10,并进行下一次相加
*/
c = c > 9
}
return res.replace(/^0+/, '')
} |
点赞👍 |
膜拜 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给大家分享一个我百度出来的一个范例,我看的不是很懂,但是觉得写得真心简洁而且好,已经在测试案例中测试通过了!!!
The text was updated successfully, but these errors were encountered: