高精度乘法
把问题简单化,将第二个乘数当作一个元素就好,其他的与加法无异
要注意每次对进位的处理
C++ 代码
#include <iostream>
#include <vector>
using namespace std;
bool cmp(vector<int>& A,vector<int>& B){
if(A.size() != B.size()){
return A.size() > B.size();
}else{
for(int i = A.size() - 1;i >= 0; --i ){
if(A[i] != B[i])
return A[i] > B[i];
}
}
return true;
}
//在这里保证A > B
vector<int> myminus(vector<int>& A,vector<int>& B){
vector<int> res;
int e = 0;
for(int i = 0;i < A.size(); ++i){
int t = 0;
t = t + e + A[i];
if(i < B.size()) t -= B[i];
if(t < 0) e = -1;
else e = 0;
res.push_back((t + 10) % 10);
}
while(res.size() > 1 && res.back() ==0) res.pop_back();
return res;
}
int main(){
string a,b;
cin>>a>>b;
vector<int>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');
if(cmp(A,B)){
auto C = myminus(A,B);
for(int i = C.size() - 1; i >= 0;--i) cout<<C[i];
}else{
auto C = myminus(B,A);
cout<<"-";
for(int i = C.size() - 1; i >= 0;--i) cout<<C[i];
}
return 0;
}