Adi - 9 months ago 83

C++ Question

I am trying to add two big integers. Here is a function I have made.

`s1`

`s1.length()`

`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;

}

Answer

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.