---
# System prepended metadata

title: \#415 Add Strings
tags: [leetcode, leetcode-easy]

---

# \#415 Add Strings
## *實作"字串加法": 傳入兩個字串型態的非負整數, 回傳兩數相加後的結果, 限制不得將傳入的變數直接轉換為整數後相加*
## Log
 - build 20210814 by syhuang

## 初見
 - 跑迴圈對每個字元轉整數後相加, 並用一變數紀錄上一個加總結果是否進位來判斷這次加總是否要+1
 - leetcode submit runtime 10%, memory 10%
```javascript=
var addStrings = function(num1, num2) {
    let i = num1.length;
    let j = num2.length;
    let carry = false;
    let result = '';
    for(; i>0 || j>0; i--,j--){
        let sum = 0;
        let n1 = 0;
        let n2 = 0;
        if(i>0 && j>0) sum = parseInt(num1[i-1]) + parseInt(num2[j-1]);
        else if(i>0) sum = parseInt(num1[i-1]);
        else if(j>0) sum = parseInt(num2[j-1]);
        if(carry){
            sum+=1;
            carry = false;
        }
        if(sum>9){
            sum-=10;
            carry = true;
        }
        result = sum.toString() + result;
    }
    if(carry) result = '1'+result;
    return result;
};
```
## 備註
- 參考javascript多種解法, 發現多數類似且速度較慢, 目前發現較快的方式是把字串轉為字元陣列後再處理([參考](https://leetcode.com/problems/add-strings/discuss/1299912/Javascript-Easy-and-Accepted-Solution-or-Runtime-76-ms-or-97.57-Faster))
## 參考
###### tags: `leetcode`, `leetcode-easy`