AcWing 793. 高精度乘法
原题链接
简单
作者:
Value
,
2020-04-25 22:09:07
,
所有人可见
,
阅读 401
方法一
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
string a;
int b;
cin >> a >> b;
reverse(a.begin(), a.end());
int cnt = 0;
string res = "";
for(int i = 0; i < a.size(); i ++ ){
int num = (a[i] - '0') * b + cnt;
if(num >= 10){
cnt = num / 10;
num %= 10;
}else cnt = 0;
res += (num + '0');
}
while(cnt){
res += (cnt % 10 + '0');
cnt /= 10;
}
reverse(res.begin(), res.end());
int flag = 1;
for(int i = 0; i < res.size(); i ++ ){
if(flag){
if(res[i] != '0'){
cout << res[i];
flag = 0;
}
}else cout << res[i];
}
if(flag == 1) cout << "0" << endl;
return 0;
}
方法二(精简版)
#include <iostream>
#include <vector>
using namespace std;
vector<int> mul(vector<int> &A, int b){
vector<int> C;
int t = 0;
for(int i = 0; i < A.size() || t; i ++ ){
if(i < A.size()) t += A[i] * b;
C.push_back(t % 10);
t /= 10;
}
while(C.size() > 1 && C.back() == 0) C.pop_back();
return C;
}
int main(){
string a;
int b; cin >> a >> b;
vector<int> A;
for(int i = a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0');
vector<int> C = mul(A, b);
for(int i = C.size() - 1; i >= 0; i -- ) cout << C[i];
return 0;
}