【笔试练习题】大数相加、大数相乘

大数相加:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

string add(string &a,string &b){
    if(a.size() < b.size())
        swap(a, b);
    string c = "0" + a;
    int carry = 0; // 进位位
    for(int i = 0; i < b.size(); ++i)
    {
        int ic = c.size() - 1 - i;
        int ia = a.size() - 1 - i;
        int ib = b.size() - 1 - i;
        c[ic] = a[ia] + b[ib] - '0' + carry;
        if(c[ic] > '9'){
            carry = 1;
            c[ic] -= 10;
        }
        else {
            carry = 0;
        }
    }
    if(carry == 1){
        for(int i = b.size(); i <= c.size() - 1; ++i)
        {
            int ic = c.size() - 1 - i;
            c[ic] += carry;
            if(c[ic] > '9'){
                carry = 1;
                c[ic] -= 10;
            }
            else {
                carry = 0;
            }
        }
    }
    if(c[0] == '0'){
        c = c.substr(1, c.size() - 1);
    }
    return c;
}

int main(int argc, char const *argv[])
{
    string a = "123";
    string b = "456";
    cout << add(a, b) << endl;
    return 0;
}

大数相乘:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

string mul(string &sa,string &sb)
{
    if(sa.size() == 0 || sb.size() == 0)
        return "";
    if(sa.size() < sb.size())
        swap(sa, sb);

    int m = sa.size();
    int n = sb.size();
    // a和b分别逆序表示字符串显示的数字(低位放前面,高位放后面), c逆序存放结果
    vector<int> a(m); 
    vector<int> b(n);
    vector<int> c(m + n, 0);
    // 逆序初始化数组
    for(int i = 0; i < m; ++i){
        a[i] = sa[m - i - 1] - '0';
    }

    for(int i = 0; i < n; ++i){
        b[i] = sb[n - i - 1] - '0';
    }

    // 计算
    for(int i = 0; i < m; ++i){
        for(int j = 0; j < n; ++j){
            c[i + j] += a[i] * b[j];
        }
    }

    for(int i = 0; i < n + m - 1; ++i){
        if(c[i] > 9){
            c[i + 1] += c[i] / 10;
            c[i] = c[i] % 10;
        }
    }

    // 除去多余的位
    if(c[m + n - 1] == 0)
        c.pop_back();

    // 逆序获得结果字符串
    string sc = "";
    for(int i = c.size() - 1; i >= 0; i--){
        sc += '0' + c[i];
    }
    return sc;
}



int main(int argc, char const *argv[])
{
    string a = "9999";
    string b = "456";
    cout << mul(a, b) << endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值