C++
$\color{#cc33ff}{— > 算法基础课题解}$
思路:
高精度除法:高精度 / 低精度
$\color{blue}{易懂版}$
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
//C = A / b 商是C,余数是r
vector<int> div(vector<int> &A, int b, int &r){ // 余数r通过引用传回去
vector<int> C; //商
r = 0; //余数
for (int i = A.size() - 1; i >= 0; i --){ //从最高位开始处理
r = r * 10 + A[i]; //个位留出来加上A的个位
C.push_back(r / b); //商就是余数整除b
r %= b; //商完之后的余数就是 余数%b
}
// 此时C从前往后存的是由高位到低(个)位
reverse(C.begin(), C.end()); //为与前面的加法,减法,乘法相同,reverse一下(主要目的是方便去除前导0)
while (C.size() > 1 && C.back() == 0) C.pop_back(); //去除前导0
return C;
}
int main(){
string a;
int b;
cin >> a >> b;// a = "123456"
vector<int> A;
for (int i = a.size() - 1; i >= 0; i --) A.push_back(a[i] - '0');//A = [6, 5, 4, 3, 2, 1]
int r;
vector<int> C;
C = div(A, b, r);
for (int i = C.size() - 1; i >= 0; i --) printf("%d", C[i]);
cout <<endl << r;
return 0;
}
$\color{red}{易记版}$
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
//C = A / b 商是C,余数是r
vector<int> div(vector<int> &A, int b, int &r){
vector<int> C;
r = 0;
for (int i = A.size() - 1; i >= 0; 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();
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');
int r;
vector<int> C;
C = div(A, b, r);
for (int i = C.size() - 1; i >= 0; i --) printf("%d", C[i]);
cout <<endl << r;
return 0;
}
orz