PAT B1017 A divided by B (20 points)

Topic link: click here

Question meaning: This question requires the calculation of A/B, where A is a positive integer with no more than 1000 digits, and B is a positive integer with 1 digit. You need to output the quotient Q and the remainder R so that A=B×Q+R holds.

Idea: High precision except single precision.

AC code:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

// A / b = C ... r, A >= 0, b > 0
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);			            // 注意是b,不是10
        r %= b;
    }
    reverse(C.begin(), C.end());		        // C与我们定义的存储方式相反
    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 = div(A, b, r);
    
    for(int i = C.size() - 1; i >= 0; --i)  cout << C[i];
    cout << " ";
    cout << r << endl;
    
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/109231207