大数相加
逐个相加Math.max(m, n)次
- Runtime: 88 ms, faster than 77.02%
- Memory Usage: 39.5 MB, less than 29.59%
- 时间复杂度
- 空间复杂度
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
let m = num1.length - 1
let n = num2.length - 1
let carry = 0
let res = ''
while(m >= 0 || n >= 0 || carry !== 0) {
let x = m < 0 ? 0 : (num1[m--] - '0')
let y = n < 0 ? 0 : (num2[n--] - '0')
let sum = x + y + carry
carry = parseInt(sum / 10)
res = (sum % 10) + res
}
return res
};
逐个相加Math.min(m, n) + 1次
- Runtime: 84 ms, faster than 89.03%
- Memory Usage: 39.5 MB, less than 27.42%
- 时间复杂度
- 空间复杂度
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
let m = num1.length - 1
let n = num2.length - 1
let res = ''
let carry = 0
while((m >= 0 && n >= 0) || carry !== 0) {
let x = m < 0 ? 0 : (num1[m--] - '0')
let y = n < 0 ? 0 : (num2[n--] - '0')
let temp = x + y + carry
carry = parseInt(temp / 10)
res = temp % 10 + res
}
if(m >= 0) res = num1.substr(0, m + 1) + res
if(n >= 0) res = num2.substr(0, n + 1) + res
return res
};
网友评论