Adi Adi -4 years ago 219
C++ Question

Biginteger Addition in C++

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

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
reports length as 1. How can I fix it ?

void addBigInteger (string s1,string s2) {
string str3;
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download