[练习] 高精度加减乘除
高精度加法
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> A,B;
vector<int> sum(vector<int>& A,vector<int>& B)
{
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(t);
return C;
}
int main()
{
string a,b;
cin >> a;
cin >> b;
for (int i = a.size()-1; i >= 0; i -- ) A.push_back(a[i]-'0');
for (int i = b.size()-1; i >= 0; i -- ) B.push_back(b[i]-'0');
auto C=sum(A,B);
for (int i = C.size()-1; i >= 0; i -- ) cout << C[i];
return 0;
}
高精度减法
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> A,B;
bool cmp(vector<int>& A,vector<int>& B)
{
if(A.size()!=B.size()) return A.size()>B.size();
for (int i = A.size()-1; i >= 0; i -- )
if(A[i]!=B[i])
return A[i]>B[i];
return true;
}
vector<int> sub(vector<int>& A,vector<int>& B)
{
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);//此时t≥0: 直接取t t<0: 取(t+10)的个位数
if(t<0) t=1;
else t=0;
}
while(C.size()>1 && C.back()==0) C.pop_back();//删去无用的"0"
return C;
}
int main()
{
string a,b;
cin >> a >> b;
for (int i = a.size()-1; i >= 0; i -- ) A.push_back(a[i]-'0');
for (int i = b.size()-1; i >= 0; i -- ) B.push_back(b[i]-'0');
vector<int> C;
if(cmp(A, B)){//保证 大减小
C=sub(A, B);
}else{
cout << '-';
C=sub(B, A);
}
for (int i = C.size()-1; i >= 0; i -- ) cout << C[i];
return 0;
}
高精度乘法
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> A,C;
void mul(vector<int>& A, int b)
{
int t=0;
for (int i = 0; i < A.size() || t>0; i ++ )
{
if(i < A.size()) t = A[i]*b+t;
C.push_back(t%10);
t /= 10;
}
while (C.size()>1 && C.back()==0) C.pop_back();
}
int main()
{
string a;
int b;
cin >> a >> b;
for (int i = a.size()-1; i >= 0; i -- ) A.push_back(a[i]-'0');
mul(A,b);
for (int i = C.size()-1; i >= 0; i -- ) cout << C[i];
return 0;
}
高精度除法
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> A,C;
void div(vector<int>& A, int b,int& r)
{
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();
}
int main()
{
string a;
int b,r=0;
cin >> a >> b;
for (int i = 0; i < a.size(); i ++ ) A.push_back(a[i]-'0');
div(A,b,r);
for (int i = C.size()-1; i >= 0; i -- ) cout << C[i];
cout << endl << r;
return 0;
}
本文来自博客园,作者:泥烟,CSDN同名, 转载请注明原文链接:https://www.cnblogs.com/Knight02/p/15799110.html