简体   繁体   English

C ++中的Biginteger加法

[英]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. s1是其中的较大字符串。 During passing the function parameter I will account for the string length. 在传递函数参数期间,我将考虑字符串长度。 The code works fine for all values except those having 10^(n). 该代码适用于除具有10 ^(n)的所有值之外的所有值。 As such it shows o/p as 2 for 100 + 2. Similarly for other power of 10 cases. 因此,对于100 + 2,它的o / p显示为2。对于其他10次幂的情况,也是如此。 When I did some digging I noticed that the for loop runs just once for these cases. 当我进行一些挖掘时,我注意到对于这些情况,for循环仅运行一次。 As such s1.length() reports length as 1. How can I fix it ? 这样s1.length()报告的长度为1。如何解决?

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 . 您需要使用str2.push_back('0')附加字符,而不是为str2[i]分配超出范围的i std::string::operator[] does not "grow" the internal storage in the string. std::string::operator[]不会“增长”字符串中的内部存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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