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
54
55
56
57
58
59
60
#include <iostream>
#include <vector>
#include <chrono>

class BigInt {
  public:
  BigInt(std::vector<uint8_t> value) {
    this->value = value;
  }
  
  BigInt(std::string str) {
    int initialZeros = 0;
    for(char c : str)
      if(c == '0') initialZeros++;
      else break;
    str.erase(0, initialZeros);
    for(int pos = str.length() - 1; pos >= 0; pos--) 
      value.push_back(str[pos] - '0');
  }
  
  std::string toString() {
    std::string str = positive? "" : "-";
    for(int pos = value.size() - 1; pos >= 0; pos--) 
      str += std::to_string(value[pos]);
    return str;
  }
  
  BigInt add(BigInt right) {
    std::vector<uint8_t> result;
    int maxLength = std::max(value.size(), right.value.size());
    result.reserve(maxLength);
    
    int carry = 0;
    for(int pos = 0; pos < maxLength; pos++) {
      int l = pos < value.size() ? value[pos] : 0;
      int r = pos < right.value.size()? right.value[pos] : 0;
      result.push_back(l + r + carry);
      if(result[pos] > 9) {
        result[pos] %= 10;
        carry = 1;
      } else carry = 0;
    }
    if(carry) result.push_back(carry);
    
    return BigInt(result);
  }
  
  std::vector<uint8_t> value;
  bool positive = true;
};

int main() {
  BigInt left("29488838");
  BigInt right("938282823");
  auto start =  std::chrono::system_clock::now();
  std::cout << left.add(right).toString() << std::endl;
  auto end = std::chrono::system_clock::now();
  std::chrono::duration<double> diff = end-start;
  std::cout << "Time used: " << diff.count() << " sec";
}