大数乘法与加法

1、大数乘法

(1)转换并反转,字符串转换为数字并将字序反转;

(2)自动移位,逐位相乘,添加最后的进位;

(3)消除多余的0;

(4)转换并反转,将计算结果转换为字符串并反转。

void reverse_str(string & str){
    size_t i = 0, j = str.size() - 1;
    char temp = 0;
    while (i < j){
        temp = str[i];
        str[i++] = str[j];
        str[j--] = temp;
    }
}

string  multiple_bigdata(string left, string right){
    reverse_str(left);
    reverse_str(right);
    string result(left.size() + right.size(), '0');
    int carry = 0;//用int传递进位
    for (size_t i = 0; i < left.size(); ++i){
        size_t res_i = i;
        for (size_t j = 0; j < right.size(); ++j){
            carry += (left[i] - '0') * (right[j] - '0') + result[res_i] - '0';
            result[res_i++] =  carry % 10 + '0';
            carry /= 10;
        }
        if (carry) result[res_i] = carry % 10 + '0';
    }
    for (size_t i = result.size() - 1; i >= 0; --i){
        if (result[i] != '0') break;
        else result.pop_back();
    }
    reverse_str(result);
    return result;
}

2、大数加法

(1)转换并反转,字符串转换为数字并将字序反转;

(2)逐位相加,添加最后的进位;

(3)消除多余的0;

(4)转换并反转,将计算结果转换为字符串并反转。

string add_bigdata(string left, string right){
    size_t i = 0;
    reverse_str(left);
    reverse_str(right);
    string result(max(left.size(), right.size()) + 1, '0');
    int carry = 0;
    for (; i < result.size(); ++i){
        if (i < left.size()) carry += left[i] - '0';
        if (i < right.size()) carry += right[i] - '0';
        result[i] = carry % 10 + '0';
        carry /= 10;
    }
    if (carry) result[++i] = carry;
    for (size_t i = result.size() - 1; i >= 0; --i){
        if (result[i] != '0') break;
        else result.pop_back();
    }
    reverse_str(result);
    return result;
}

你可能感兴趣的:(大数乘法与加法)