Skip to content

415. Add Strings 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  string addStrings(string num1, string num2) {
    string ans;
    int carry = 0;
    int i = num1.length() - 1;
    int j = num2.length() - 1;

    while (i >= 0 || j >= 0 || carry) {
      if (i >= 0)
        carry += num1[i--] - '0';
      if (j >= 0)
        carry += num2[j--] - '0';
      ans += carry % 10 + '0';
      carry /= 10;
    }

    reverse(begin(ans), end(ans));
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public String addStrings(String num1, String num2) {
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    int i = num1.length() - 1;
    int j = num2.length() - 1;

    while (i >= 0 || j >= 0 || carry > 0) {
      if (i >= 0)
        carry += num1.charAt(i--) - '0';
      if (j >= 0)
        carry += num2.charAt(j--) - '0';
      sb.append(carry % 10);
      carry /= 10;
    }

    return sb.reverse().toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def addStrings(self, num1: str, num2: str) -> str:
    ans = []
    carry = 0
    i = len(num1) - 1
    j = len(num2) - 1

    while i >= 0 or j >= 0 or carry:
      if i >= 0:
        carry += int(num1[i])
      if j >= 0:
        carry += int(num2[j])
      ans.append(str(carry % 10))
      carry //= 10
      i -= 1
      j -= 1

    return ''.join(reversed(ans))