算术地添加两个字符串

时间:2013-05-25 02:00:00

标签: c++ string

我正在尝试实现一个函数来添加存储在字符串中的两个过大(比如说1000位长)的数字。我在转换正确方面遇到问题,因此我可以正确添加数字。

到目前为止,这就是我所做的:

string addBegin (string low, string high, int diff)
{
    for (int i = 0; i <= diff; i++)
        low = "0" + low;
    high = "0" + high;

    cout << "low: " << low << "\nhigh: " << high << endl;

    string result;
    int sum, carry = 0;

    for (int i = low.length()-1; i >= 0; i--)
    {
        sum = (int)low[i] + (int)high[i] + carry;
        carry = 0;
        if (sum > 9)
        {
            sum -= 10;
            carry = 1;
        }
        result = to_string(sum) + result;
    }

    return result;
}

string add (string a, string b)
{
    int diff = a.length() - b.length();

    if (diff <= 0) return addBegin(a, b, abs(diff));
    else return addBegin(b, a, diff);
}

int main (void)
{
    string x = add("52","205");
    cout << "result: " << x << endl;

    return 0;
}

输出:

low: 0052
high: 0205 //the first zero is for potential carry
result: 87899293 //wrong, should be 0257

此处的结果由4个数字组成:87899293。这显然是错误的,我用ASCII值做了一些不必要的添加。任何想法如何使这项工作?或者,在任何可能的情况下,是否有一些可笑的简单方法来添加两个veeeeery长数字?

3 个答案:

答案 0 :(得分:5)

    sum = (int)low[i] + (int)high[i] + carry;

这会将字符编码的值添加到例如ASCII。您想从编码中减去'0'以获取数值。

    sum = low[i] - '0' + high[i] - '0' + carry;

答案 1 :(得分:4)

在进行数学运算时,请不要忘记从'0'low[i]减去high[i]

(int)low[i] 0x30 .. 0x39用于字符'0' .. '9'

答案 2 :(得分:1)

问题是您使用

sum = (int)low[i] + (int)high[i] + carry;

应该是

sum = low[i] - '0' + high[i] - '0' + carry;