简体   繁体   中英

I can't figure out what's going wrong when I try to add 2 big strings

I tried this question by using big integer library in c++ and it works completely fine and when I try to do this using one integer at a time from both the strings

I get a run time error and I did try to debug it by including cout statements in the code but everything seems fine.

 string addStrings(string num1, string num2) {
        string res="";
        int n=num1.size();
        int m=num2.size();
        int carry=0;
        int j;
        for(int i=n-1,j=m-1;i>=0 || j>=0;i--,
            j--){
            int a;
            if(i>=0){
                a=((int)(num1[i])-48);
            }
            else {
                a=0;
            }
            int b; 
            if(j>=0){
                b=((int)(num2[j])-48);
            }
            else{
                b=0;
            }
            cout<<num1[i]<<" "<<num2[i]<<endl;
            cout<<a<<" "<<b<<endl;
            int sum=carry+a+b;
            int u=sum%10;
            res+=u;
            carry=sum/10;
        }
        res+=carry;
        cout<<res<<endl;
        reverse(res.begin(),res.end());
      
    return res;
    }

You declare a std::string called res in your program, which you want to return from your function. Everything works fine until this line:

res += u;

In this line, you attempt to add an int to a string , which will return unexpected results. To fix this, you can use res.push_back(u + '0') instead (this converts u to a char then appends it to res : no unexpected results).

You also do the same thing 3 lines down, where you type res += carry; , so make sure to fix that too.

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