#include<bits/stdc++.h>usingnamespace std;constint maxn =1e4+5;// 时间复杂度是O(n^2),最多到1e4int ans[maxn];// 保存答案int cnt;// 数组长度voidmulty(string a, string b){
cnt =0;memset(ans,0,sizeof ans);reverse(a.begin(), a.end());reverse(b.begin(), b.end());int n = a.size(), m = b.size();for(int i =0; i < n; i++){for(int j =0; j < m; j++){
ans[i + j]+=(a[i]-'0')*(b[j]-'0');}}for(int i =0; i < m + n; i++){
ans[i +1]+= ans[i]/10;
ans[i]%=10;}
cnt = m + n;while(ans[cnt]==0) cnt--;
cnt++;reverse(ans, ans + cnt);}voidadd(string a, string b){memset(ans,0,sizeof ans);
cnt =0;reverse(a.begin(), a.end());reverse(b.begin(), b.end());int n = a.size(), m = b.size(), t =0;for(int i =0, j =0; i < n || j < m; i++, j++, cnt++){if(i < n) t += a[i]-'0';if(j < m) t += b[j]-'0';
ans[cnt]= t %10;
t /=10;}if(t) ans[cnt++]= t;reverse(ans, ans + cnt);}intmain(){
string a, b;
cin >> a >> b;add(a, b);for(int i =0; i < cnt;i ++){printf("%d", ans[i]);}return0;}
除法,适用于被除数是整形的情况。
#include<bits/stdc++.h>usingnamespace std;
vector<int>div(vector<int>&a,int b){int m = a.size();
vector<int>c;int j =0;int mod =0;int bg =1;while(j < m){int x = mod;while(j < m && x < b){
x = x *10+ a[j];if(x < b &&!bg) c.push_back(0);
j++;}
bg =0;if(x >= b) c.push_back(x / b);//printf("x = %d push_%d mod = %d\n", x, x / b, x % b);
mod = x % b;}
c.push_back(mod);//最后一个存放mod;return c;}
vector<int>change(string &s){
vector<int>ans;int n = s.size();for(int i =0; i < n; i++){
ans.push_back(s[i]-'0');}return ans;}intmain(){
string s1;int b;getline(cin, s1);
cin >> b;
vector<int>a =change(s1);
vector<int>c =div(a, b);for(int i =0; i < c.size()-1; i++)printf("%d", c[i]);if(c.size()==1)printf("0");printf("\n%d", c[c.size()-1]);}
作者:Empty_94
链接:https://www.acwing.com/activity/content/code/content/1840553/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
减法
#include<iostream>#include<vector>#include<cstring>usingnamespace std;
vector<int>sub(vector<int> a, vector<int> b){
vector<int> res;int t =0;for(int i =0; i < a.size(); i++){int x = a[i]+ t;if(i < b.size())
x -= b[i];if(x >=0){
res.push_back(x);
t =0;}else{
res.push_back(x +10);
t =-1;}}while(res.size()>1&& res.back()==0) res.pop_back();return res;}booljudge(string &a, string &b){if(a.size()> b.size())returntrue;elseif(a.size()< b.size())returnfalse;elsereturn a > b;}intmain(){
string n, m;
cin >> n >> m;
vector<int> a, b;bool flag =true;if(judge(m, n)){
flag =false;
string t = m;
m = n;
n = t;}for(int i = n.size()-1; i >=0; i--)
a.push_back(n[i]-'0');for(int i = m.size()-1; i >=0; i--)
b.push_back(m[i]-'0');auto res =sub(a, b);if(!flag)
cout <<'-';for(int i = res.size()-1; i >=0; i--)printf("%d", res[i]);return0;}