C++ Algorithm to Add Two Big Integers (of String Type)


Given two strings a, and b, both representing an integer, add them and return it in the same string representation.

Bonus: can you implement the addition directly, instead of using eval or built-in big integers?

Constraints
n ≤ 200 where n is the length of a
m ≤ 200 where m is the length of b
Example 1
Input

a = “12”
b = “23”
Output

“35”
Explanation
12 + 23 = 35

Algorithms to Add Two Big Integers

To add two big integers, we need to start from the least significant digits (rightmost) and then carry over the digit sums.

string solve(string a, string b) {
    int c = 0;
    int la = a.size() - 1;
    int lb = b.size() - 1;
    string ans = "";
    while ((la >= 0) || (lb >= 0) || (c > 0)) {
        int v = c;
        if (la >= 0) v += a[la --] - '0';
        if (lb >= 0) v += b[lb --] - '0';
        ans = ((char)(48 + v % 10)) + ans;
        c = v/10;
    }
    return ans;
}

The above C++ only uses one while loop – at the cost of checking three conditions each iteration. You can solve this puzzle using eval or BigInteger class, or in Python easily.

–EOF (The Ultimate Computing & Technology Blog) —

261 words
Last Post: NUC: All-In-One Raspberry PI 400 Kit - Personal Computer Kit with Raspbian OS
Next Post: C++ Run-Length Decoding Algorithm

The Permanent URL is: C++ Algorithm to Add Two Big Integers (of String Type) (AMP Version)

Leave a Reply