Julfikar
Julfikar

Reputation: 1423

C++ how to add two numbers in decimal system?

I have two numbers 999 and 2. I want to add them in the decimal system, ex:

999
 +2
---
1001

First, I am adding 2 with 9 and I'm getting 11 so I'm printing 1 and carrying out 1 for next 9. Similarly getting 10, printing 0 and carrying out 1 for next 9 and adding them. It's like how we used to do addition in our school level. However, now I have to do the same in C++. For this, first I'm splitting 999 and storing in an array. After that adding 2 with the last element of array. If the sum is more than or equal 10, I'm keeping sum%10 for the next elements in the array. The problem is, I don't know how can I add the sum%10 with the next elements and keep checking if they are more than or equal 10 at the same time for rest of the elements?

Upvotes: 1

Views: 303

Answers (1)

Ashot
Ashot

Reputation: 10969

Assume a and b contain digits of numbers in reverse order. This code will add b to a, i.e. a = a+b.

int base = 10;
int carry = 0;
for (size_t i=0; i<max(a.size(),b.size()) || carry; ++i) {
    if (i == a.size())
        a.push_back (0);
    a[i] += carry + (i < b.size() ? b[i] : 0);
    carry = a[i] >= base;
    if (carry)  a[i] -= base;
}

Upvotes: 1

Related Questions