You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function charSum(num1,num2){
let i = num1.length-1;
let j = num2.length-1;
let k = ''
while(i>=0&&j>=0){
let n1 = num1.charAt(i)%10
let n2 = num2.charAt(j)%10
let total =n1+n2
k = total+k
i--,
j--
}
if(i>=0){
k = num1.slice(0,i+1)+k
}
if(j>=0){
k = num2.slice(0,j+1)+k
}
return k
}
console.log(charSum("111111",'2222'))
function twoSumStr(str1,str2){
let i = str1.length-1,j=str2.length-1
let total = ''
while(i>=0&&j>=0){
let c1 = (str1.charAt(i))%10
let c2 = (str2.charAt(j))%10
let t = c1+c2
total=t+total
i--
j--
}
if(i>=0){
total = str1.slice(0,i+1)+total
}
if(j>=0){
total = str2.slice(0,j+1)+total
}
return total
}
console.log(twoSumStr("111","2222"))
Activity
[-]Facebook&字节&leetcode415. 字符串相加[/-][+]Facebook&字节&leetcode415:字符串相加[/+]ricosmall commentedon May 6, 2020
上代码
mingju0421 commentedon May 6, 2020
hecun0000 commentedon May 6, 2020
sisterAn commentedon May 6, 2020
解答:从低位开始相加
从
num1,num2的尾部开始计算,模拟人工加法,保存到tmp中;计算
tmp的个位数,并添加到result的头部,这里的result是string类型,不是number类型;计算进位,改成
tmp,进行下次循环索引溢出处理:循环结束,根据
tmp判断是否有进位,并在result头部添加进位 1返回
result代码实现:
复杂度分析:
leetcode
13001920223 commentedon May 7, 2020
1、新建立双指针 i 、j,倒序循环两个数组
2、判断两数相加是否大于10,大于则进1,缓存 (result % 10)
3、循环结束判断move是否有值,有则加上,没有直接return
空间复杂度: 循环num1, num2,则空间复杂度O(n)
空间复杂度: result缓存结果,常数级复杂度O(1)
itxuye commentedon May 8, 2020
qianlongo commentedon Aug 16, 2020
xllpiupiu commentedon Oct 6, 2021
AlexZhang11 commentedon May 24, 2024
function charSum(num1,num2){ let i = num1.length-1; let j = num2.length-1; let k = '' while(i>=0&&j>=0){ let n1 = num1.charAt(i)%10 let n2 = num2.charAt(j)%10 let total =n1+n2 k = total+k i--, j-- } if(i>=0){ k = num1.slice(0,i+1)+k } if(j>=0){ k = num2.slice(0,j+1)+k } return k } console.log(charSum("111111",'2222'))AlexZhang11 commentedon May 31, 2024
function twoSumStr(str1,str2){ let i = str1.length-1,j=str2.length-1 let total = '' while(i>=0&&j>=0){ let c1 = (str1.charAt(i))%10 let c2 = (str2.charAt(j))%10 let t = c1+c2 total=t+total i-- j-- } if(i>=0){ total = str1.slice(0,i+1)+total } if(j>=0){ total = str2.slice(0,j+1)+total } return total } console.log(twoSumStr("111","2222"))