Files
  • main.cpp
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>

using std::string;

string addStrings(string a, string b) {
  std::stringstream ss;
  auto i = a.rbegin();
  auto j = b.rbegin();
  int carry = 0;
  while (i != a.rend() || j != b.rend()) {
    const int x = (i == a.rend()) ? 0 : (*i++ - '0');
    const int y = (j == b.rend()) ? 0 : (*j++ - '0');
    const int s = x + y + carry;
    ss << (s % 10);
    carry = s / 10;
  }
  if (carry != 0) {
    ss << 1;
  }
  std::string ret = ss.str();
  std::reverse(ret.begin(), ret.end());
  return ret;
}

string addStringsNoIter(string a, string b) {
  string result;
  int carry = 0;
  size_t i = 0;
  size_t j = 0;
  while (i < a.size() || j < b.size()) {
    int s = carry;
    if (i < a.size()) {
      s += (a[a.size() - 1 - i++] - '0');
    }
    if (j < b.size()) {
      s += (b[b.size() - 1 - j++] - '0');
    }
    carry = s / 10;
    result = std::to_string(s % 10) + result;
  }
  if (carry) {
    result = "1" + result;
  }
  return result;
}

int main() {
  std::cout << (addStrings("12345", "987654321") == "987666666") << std::endl;
  std::cout << (addStringsNoIter("12345", "987654321") == "987666666") << std::endl;
}