zoukankan      html  css  js  c++  java
  • 大数相加相乘

    用乘法行列式多次相乘多次相加,时间复杂度为O(nm),n,m分别为两个数字长度。

    #include<stdio.h>
    #include<iostream>
    #include<string>
    #include<sstream>
    using namespace std;
    
    string a,b,ans,zero,product;///输入a,b,ans是最终答案,zero是乘法行列式补零用的,product暂时存储单位数乘积
    int len1,len2,cha,maxx;
    int s,r;///s是本位,r是进位
    
    string add(string a,string b)///字符串大数相加
    {
        string res="";
        s=0;r=0;
        len1=a.size();
        len2=b.size();
    
        if(len1>=len2)
        {
            cha=len1-len2;
            for(int i=0;i<cha;i++)
                b="0"+b;
        }
        else
        {
            cha=len2-len1;
            for(int i=0;i<cha;i++)
                a="0"+a;
        }
        maxx=max(len1,len2);
        for(int i=maxx-1;i>=0;i--)
        {
            s=(a[i]-'0'+b[i]-'0'+r)%10;///先加上上次的进位
            r=(a[i]-'0'+b[i]-'0'+r)/10;///本次进不进位,进位则是1,不进位则是0
            res=(char)(s+'0')+res;
        }
        if(r)
            res="1"+res;    ///最左边需不需要进位
        return res;
    }
    
    string trans(int a)  ///整型转化为string型,需要头文件sstream
    {
        stringstream ss;///中转站
        string res;
        ss<<a;
        ss>>res;
        return res;
    }
    
    string multiplication(string a,char b)///字符串数字*单个字符
    {
        s=r=0;
        string res="";
        int x,y=b-'0';
        int len=a.size();
        for(int i=len-1;i>=0;i--)
        {
            x=a[i]-'0';
            s=(x*y+r)%10;
            r=(x*y+r)/10;
            res=(char)(s+'0')+res;
        }
        if(r)
            res=char(r+'0')+res;
        return res;
    }
    
    int main()
    {
        int t;
        cin>>t;
        for(int i=1;i<=t;i++)
        {
            cin>>a>>b;
            ans="";
            zero="";
            len2=b.size();
            for(int j=len2-1;j>=0;j--)
            {
                product=multiplication(a,b[j])+zero;
                ans=add(ans,product);
                zero=zero+'0';  ///每往左进一位,乘法多补一个0
            }
            cout<<ans<<endl;
        }
        return 0;
    }
  • 相关阅读:
    nohub和 2>&1 &
    postman
    ximd 破解版
    B树和B+树的插入、删除图文详解
    漫画叙述B+树和B-树,很值得看!
    数据库 操作的几个问题记录
    推送实现 应用未启动情况下的自定义声音播放
    collectionView reloadData时 点击问题
    强制横屏或者竖屏
    wkWebView 或者 webView 在客户端隐藏某些布局的方法
  • 原文地址:https://www.cnblogs.com/shoulinniao/p/10258294.html
Copyright © 2011-2022 走看看