首页 > 其他分享 >高精度计算_vector

高精度计算_vector

时间:2022-11-13 22:58:12浏览次数:51  
标签:begin end reverse 高精度 int vector 计算 return

#include<bits/stdc++.h>
using namespace std;
// return a+b;
vector<int> add(vector<int>&a,vector<int>&b){
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    vector<int> c;
    int t=0;
    for(int i=0; i<a.size()||i<b.size(); i++){
        if(i<a.size()) t+=a[i];
        if(i<b.size()) t+=b[i];
        c.push_back(t%10), t/=10;
    }
    if(t) c.push_back(1);
    reverse(c.begin(),c.end());
    return c;
}
// return a-b;
vector<int> sub(vector<int>&a,vector<int>&b){
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    vector<int> c; int t=0;
    for(int i=0; i<a.size(); i++){
        t = a[i]-t;
        if(i<b.size()) t-=b[i];
        c.push_back((t+10)%10);
        if(t<0) t=1; else t=0;
    }
    while(c.size()>1 && c.back()==0) c.pop_back();
    reverse(c.begin(),c.end());
    return c;
}
// return a>=b;
bool cmp(vector<int>&a,vector<int>&b){
    if(a.size()!=b.size()) return a.size()>b.size();
    for(int i=0; i<a.size(); i++){
        if(a[i]!=b[i]) return a[i]>b[i];
    }
    return 1;
}
// return a*b;
vector<int> mul(vector<int>&a,int&b){
    reverse(a.begin(),a.end());
    vector<int> c; int t=0;
    for(int i=0; i<a.size()||t; i++){
        if(i<a.size()) t += a[i]*b;
        c.push_back(t%10);
        t/=10;
    }
    while(c.size()>1 && c.back()==0) c.pop_back();
    reverse(c.begin(),c.end());
    return c;
}
// return a/b, r=a%b
vector<int> div(vector<int>&a,int&b,int &r){
    vector<int> c; r=0;
    for(int i=0; i<a.size(); i++){
        r = r*10+a[i];
        c.push_back(r/b);
        r %= b;
    }
    reverse(c.begin(),c.end());
    while(c.size()>1 &&c.back()==0) c.pop_back();
    reverse(c.begin(),c.end());
    return c;
}
int main(){
    string a; int b; cin>>a>>b;
    vector<int> va,vb,vc;
    for(int i=0; i<a.size(); i++) va.push_back(a[i]-'0');
    int r;
    vc=div(va,b,r);
    for(auto u:vc) cout<<u; cout<<endl<<r;
}

标签:begin,end,reverse,高精度,int,vector,计算,return
From: https://www.cnblogs.com/hellohebin/p/16887569.html

相关文章