Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- string add_two_numbers(string a, string b) {
- if((int) b.size() > (int) a.size()) {
- swap(a, b);
- }
- int carry = 0;
- string res = "";
- int i = (int) a.size() - 1, j = (int) b.size() - 1;
- while(j >= 0) {
- int digit_a = (int) (a[i] - '0');
- int digit_b = (int) (b[j] - '0');
- int sum = digit_a + digit_b + carry;
- if(sum < 10) {
- res += (sum + '0');
- }
- else {
- carry = 1;
- res += ((sum % 10) + '0');
- }
- i--;
- j--;
- }
- while(i >= 0) {
- int digit_a = (int) (a[i] - '0');
- int sum = digit_a + carry;
- if(sum < 10) {
- carry = 0;
- res += (sum + '0');
- }
- else {
- carry = 1;
- res += ((sum % 10) + '0');
- }
- i--;
- }
- if(carry == 1) {
- res += "1";
- }
- reverse(res.begin(), res.end());
- return res;
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cout << add_two_numbers("999", "999");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement