[Codewars] Adding Big Numbers

Adding Big Numbers

  • Time :
  • Space :
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

#include <string>

std::string add(const std::string& a, const std::string& b) {
std::string ca = a, cb = b;
std::reverse(std::begin(ca), std::end(ca));
std::reverse(std::begin(cb), std::end(cb));
std::string res = "";
int carry = 0, i = 0;
while(i < ca.length() and i < cb.length()) {
int now = carry + ca[i] - '0' + cb[i] - '0';
res.push_back(now % 10 + '0');
carry = now / 10;
i += 1;
}
while(i < ca.length()) {
int now = carry + ca[i] - '0';
res.push_back(now % 10 + '0');
carry = now / 10;
i += 1;
}
while(i < cb.length()) {
int now = carry + cb[i] - '0';
res.push_back(now % 10 + '0');
carry = now / 10;
i += 1;
}
if(carry) res.push_back(carry + '0');
std::reverse(std::begin(res), std::end(res));
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/10/PS/Codewars/adding-big-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.