题目
<4kyu>Sum Strings as Numbers
Given the string representations of two integers, return the string representation of the sum of those integers.
A string representation of an integer will contain no characters besides the ten numerals “0” to “9”.
给定两个整数的字符串体现形式,返回这些整数之和的字符串体现形式。
(注:这两个字符串将不包罗除“0”到“9”之外的任何字符。)
例子
- sumStrings('1','2') // => '3'sumStrings('','5') // => '5'sumStrings('001','5') // => '6'sumStrings('50095301248058391139327916261','81055900096023504197206408605') // => '131151201344081895336534324866'
复制代码 题解一
- // 题解一:function sumStrings(a,b) { var result = ''; var remainder = 0; if(a.length < b.length) { var c = a; a = b; b = c; } for(let i=1;i0 ? parseInt(a.substr(a.length-i,1)) : 0) + (b.length-(i-1)>0 ? parseInt(b.substr(b.length-i,1)) : 0) + remainder; // 求和后去取余,就是该位要生存的数字 result = sum%10 + result // 盘算余数 remainder = parseInt(sum/10) // 如果到了最左边,即a的第一位,余数还大于0,则直接加上余数 if(remainder > 0 && i == a.length) result = remainder + result; } return result.replace(/\b(0+)/gi,""); // 去除字符串前面的0}
复制代码 题解二(Best Practices)
- // 题解二:function sumStrings(a, b) { var res = '', c = 0; a = a.split(''); b = b.split(''); while (a.length || b.length || c) { c += ~~a.pop() + ~~b.pop(); res = c % 10 + res; c = c > 9; } return res.replace(/^0+/, '');}
复制代码 小伙伴们有别的更好的解法,接待评论区提出交换~
来源:https://blog.csdn.net/weixin_36270908/article/details/111994142
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |