> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/google/415-add-strings.md).

# 415 Add Strings

## 415. [Add Strings](https://leetcode.com/problems/add-strings/description/)

## 1. Question

Given two non-negative integers`num1`and`num2`represented as string, return the sum of`num1`and`num2`.

**Note:**

1. The length of both`num1`and`num2`is < 5100.
2. Both`num1`and`num2`contains only digits`0-9`.
3. Both`num1`and`num2`does not contain any leading zero.
4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly.

## 2. Implementation

```
class Solution {
    public String addStrings(String num1, String num2) {
        if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) {
            return "";
        }

        StringBuilder res = new StringBuilder();

        int index1 = num1.length() - 1;
        int index2 = num2.length() - 1;
        int sum = 0;

        while (index1 >= 0 || index2 >= 0) {
            int digit1 = index1 >= 0 ? num1.charAt(index1) - '0' : 0;
            int digit2 = index2 >= 0 ? num2.charAt(index2) - '0' : 0;
            sum += digit1 + digit2;
            res.append(sum % 10);
            sum /= 10;
            --index1;
            --index2;
        }

        if (sum != 0) {
            res.append(sum);
        }
        return res.reverse().toString();
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(Max(m,n)), m是num1的长度, n是num2的长度, 空间复杂度O(Max(m, n))
