高精度加减乘除法

题目连接

A+B:
题目描述
高精度加法,相当于a+b problem,不用考虑负数.

输入格式
分两行输入。a,b \leq 10^{500}a,b≤10
500

输出格式
输出只有一行,代表a+ba+b的值

输入输出样例
输入 #1

1
1

输出 #1

2

输入 #2

1001
9099

输出 #2

10100

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string add(string a,string b){
    if(a.size() < b.size())  return add(b,a);
    string res;
    int t=0;
    
    for(int i=a.size()-1,j=b.size()-1;i>=0;i--){
        t+=a[i]-'0';
        if(j>=0) t+=b[j--]-'0';
        res.push_back(t%10+'0');
        t/=10;
    }
    if(t)   res.push_back('1');
    reverse(res.begin(),res.end());
    return res;
}

int main(){
    string a,b;
    cin >> a >> b;
    
    cout << add(a,b) << endl;
    return 0;

}

题目链接
A-B:
题目描述
高精度减法。

输入格式
两个整数 a,ba,b(第二个可能比第一个大)。

输出格式
结果(是负数要输出负号)。

输入输出样
输入
2
1
输出
1
说明/提示
20%20% 数据 a,ba,b 在 long long 范围内;
100%100% 数据 0<a,b\le 10^{10086}0<a,b≤10
10086

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

bool cmp(string a, string 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 false;
}

string sub(string a,string b){
   bool flag=false;
   if(cmp(a,b)){
       flag=true;
       swap(a,b);
   }
   int t =0;
   string res;
   
   for(int i=a.size()-1,j=b.size()-1;i>=0;i--){
       t+=a[i]-'0';
       if(j>=0) t-=b[j--]-'0';
       res.push_back((t+10)%10+'0');
       t=t<0?-1:0;
   }
   while(res.size()>1&& res.back()=='0') res.pop_back();
   reverse(res.begin(),res.end());
   
   if(flag)    return "-"+res;
   return res;
   
}

int main(){
   string a,b;
   cin>>a>>b;
   
   cout << sub(a,b) << endl;
   return 0;
}

题目链接
A/B:

题目描述
输入两个整数 a,ba,b,输出它们的商。

输入格式
两行,第一行是被除数,第二行是除数。

输出格式
一行,商的整数部分。

输入输出样例
输入 #1复制
10
2
输出 #1复制
5
说明/提示
0\le a\le 10^{5000}0≤a≤10
5000
,1\le b\le 10^91≤b≤10
9

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string div(string a, int b){
    if(a=="0")  return "0";
    string res;
    
    long long t=0;
    for(int i=0;i<a.size();i++){
        t=t*10+(a[i]-'0');
        res.push_back(t/b+'0');
        t%=b;
    }
    reverse(res.begin(),res.end());
    while(res.size()>1 && res.back()=='0') res.pop_back();
    
    reverse(res.begin(),res.end());
    return res;
}

int main(){
    string a;
    int b;
    cin>>a>>b;
    cout << div(a,b) << endl;
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值