题目连接
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;
}