#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
using namespace std;
std::vector<int> getDigits(std::string str)
{
std::vector<char> vec(str.begin(), str.end());
std::vector<int> digits;
for (char c : vec)
digits.push_back(c - '0');
std::reverse(digits.begin(), digits.end());
return digits;
}
std::string print(std::vector<int> const& digits)
{
std::string result;
bool nonZero = false;
for (int i = digits.size() - 1; i>=0; --i)
{
if (digits[i] > 0)
nonZero = true;
if (nonZero)
result.push_back(digits[i] + '0');
}
return result;
}
std::string sum(std::string const& first, std::string const& second)
{
std::vector<int> firstDigits = getDigits(first);
std::vector<int> secondDigits = getDigits(second);
int maxLength = std::max(firstDigits.size(), secondDigits.size()) + 1;
firstDigits.resize(maxLength, 0);
secondDigits.resize(maxLength, 0);
std::vector<int> result(maxLength, 0);
bool addOne = false;
for (int i = 0; i < maxLength; ++i)
{
int sum = firstDigits[i] + secondDigits[i];
if (addOne)
sum++;
addOne = (sum>=10);
result[i] = sum % 10;
}
return print(result);
}
int main()
{
ios::sync_with_stdio(false);
string first;
string second;
std::cin >> first >> second;
std::cout << sum(first, second);
};
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 61 | #include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #include <set> using namespace std; std::vector<int> getDigits(std::string str) { std::vector<char> vec(str.begin(), str.end()); std::vector<int> digits; for (char c : vec) digits.push_back(c - '0'); std::reverse(digits.begin(), digits.end()); return digits; } std::string print(std::vector<int> const& digits) { std::string result; bool nonZero = false; for (int i = digits.size() - 1; i>=0; --i) { if (digits[i] > 0) nonZero = true; if (nonZero) result.push_back(digits[i] + '0'); } return result; } std::string sum(std::string const& first, std::string const& second) { std::vector<int> firstDigits = getDigits(first); std::vector<int> secondDigits = getDigits(second); int maxLength = std::max(firstDigits.size(), secondDigits.size()) + 1; firstDigits.resize(maxLength, 0); secondDigits.resize(maxLength, 0); std::vector<int> result(maxLength, 0); bool addOne = false; for (int i = 0; i < maxLength; ++i) { int sum = firstDigits[i] + secondDigits[i]; if (addOne) sum++; addOne = (sum>=10); result[i] = sum % 10; } return print(result); } int main() { ios::sync_with_stdio(false); string first; string second; std::cin >> first >> second; std::cout << sum(first, second); }; |
English