简体   繁体   中英

Biginteger Addition in C++

I am trying to add two big integers. Here is a function I have made. s1 is the larger string in it. During passing the function parameter I will account for the string length. The code works fine for all values except those having 10^(n). As such it shows o/p as 2 for 100 + 2. Similarly for other power of 10 cases. When I did some digging I noticed that the for loop runs just once for these cases. As such s1.length() reports length as 1. How can I fix it ?

void addBigInteger (string s1,string s2) {
    string str3;
    reverse(s1.begin(),s1.end());
    reverse(s2.begin(),s2.end());
    int temp = 0,carry=0,i;
    for (i=0;i<s1.length();i++) {

        if ((i+1) > s2.length())
            s2[i] = '0';

        temp = s1[i]-'0'+s2[i]-'0'+carry;
        str3[i] = temp%10 + '0';
        carry = temp/10;
    }
    while (carry!=0) {
        str3[i++] = carry%10 + '0';
        carry = carry/10;
    }

    for (i;i>=0;i--) {
        cout << str3[i];
    }
    cout << endl;
}

You need to use str2.push_back('0') to append characters instead of assigning str2[i] with out-of-bound i . std::string::operator[] does not "grow" the internal storage in the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM