/*****************************************************问题描述*************************************************
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
给定2个字符串,代表2个整数,返回这2个数字相加的字符串表示形式
/*****************************************************我的解答*************************************************
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
var num1Array = num1.split('').reverse();
var num2Array = num2.split('').reverse();
var result = [];
var maxArrayLength = Math.max(num1Array.length,num2Array.length);
var carry = 0;
for(var index = 0; index < maxArrayLength; index++)
{
var number1 = num1Array[index] || 0;
var number2 = num2Array[index] || 0;
var pushNum = ((number1 - 0) + (number2 - 0) + carry) % 10;
carry = parseInt(((number1 - 0) + (number2 - 0) + carry) / 10);
result.push(pushNum);
}
if(carry !== 0)
{
result.push(1);
}
return result.reverse().join('');
};
leetCode刷题记录53_415_Add Strings
最新推荐文章于 2020-11-23 13:42:56 发布