點(diǎn)擊查看代碼
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> div(vector<int>& A, int b, int &r)
{
vector<int> C;
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 = 0;
auto C = div(A, b, r);
for (int i = C.size() - 1; i >= 0; i --) printf("%d", C[i]);
cout << endl << r << endl;
return 0;
}
- 用 r 記錄余數(shù),每計(jì)算一個(gè)新的除法時(shí),res = res * 10 + A[ i ],res * 10 類似于除法操作中把余數(shù)挪下來這個(gè)操作;
- C 記錄的是從高位到低位,要進(jìn)行反轉(zhuǎn),然后去除前導(dǎo)的 0;
- div 關(guān)于 r 的參數(shù)要傳入 & r;
本文摘自 :https://www.cnblogs.com/