Last active
March 22, 2018 18:19
-
-
Save gladilindv/a69fbc4b61c952a7d975a82466f840bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
std::string sum(const std::string& a, const std::string& b) | |
{ | |
std::string res(std::max(a.size(), b.size()) + 1, '0'); | |
auto iterA = a.rbegin(); | |
auto iterB = b.rbegin(); | |
auto iter = res.rbegin(); | |
static const auto addIter = [&iter](decltype(iterA)& iterA, const std::string& a) | |
{ | |
if(iterA != a.rend()) | |
{ | |
*iter += *iterA - '0'; | |
if(*iter > '9') | |
{ | |
auto tmpIter = iter; | |
++tmpIter; | |
*tmpIter = '1'; | |
*iter -= 10; | |
} | |
++iterA; | |
} | |
}; | |
while(iter != res.rend()) | |
{ | |
addIter(iterA, a); | |
addIter(iterB, b); | |
++iter; | |
} | |
if(res[0] == '0') | |
{ | |
res.erase(0, 1); | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment