PAT Grade B 1017 A divided by B (20 points) - two methods

topic content

This problem asks to calculate A/B, where A is a positive integer up to 1000 digits and B is a 1-digit positive integer. You need to output the quotient Q and the remainder R such that A=B×Q+R holds.

Input format:

The input gives A and B sequentially on one line, separated by 1 space.

Output format:

Output Q and R in sequence on one line, separated by 1 space.

Input sample:

123456789050987654321 7

no blank line at the end

Sample output:

17636684150141093474 3

no blank line at the end

Problem solving ideas

Method one common method

This problem is a classic problem of high-precision computing. The range of A in the problem is no more than 1000 digits, so we must not use long to violently evaluate. String type reads A, calculates each bit in the string separately, calculates one bit, and outputs one bit.

Method 2 uses vector to do

Using the characteristics of vector to facilitate insertion and deletion, the strings are stored in the vector in reverse order, and then the data is traversed and stored in the vector in turn, and the special results are processed, and finally output in reverse order.

Detailed code

method one

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    string A;
    int B;
    int Q = 0,R = 0;  //Q表示商,R表示每次运算的余数
    bool isFirst = true;
    cin>>A>>B;
    for(int i = 0;i<A.length();i++){
        Q = (R*10+A[i]-'0')/B;
//Q为0只有不在字符串的头一个且整个字符串的长度不唯一或者字符串长度为1时才输出
        if(isFirst&&A.length()>1){  
            if(Q!=0){
            cout<<Q;
            isFirst = false;
            }
        }else{
            cout<<Q;
        }
        R = (R*10+A[i]-'0')%B;
    }
    cout<<" "<<R;
}

Method Two

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector <int> div(vector <int> a,int b,int &r){
    vector <int> c;  //用于存放计算结果
    int y = 0;  
    for(int i = a.size()-1;i>=0;i--){
        y = y*10+a[i];  //y表示余数
        c.push_back(y/b);
        y=y%b;
    }
    r = y; //保留最后的余数
    reverse(c.begin(),c.end());  //c不是最后的结果,他是结果的逆序,所以逆转过来以后会存在首值为0的情况,所以我们需要提前逆转过来,删除首部的0
    while(c.size()>1&&c.back()==0) c.pop_back();
      return c;
}
int main(){
    string a;
    int b,r;
    cin>>a>>b;
    vector <int> A;
//为了方便计算,将字符串a逆着写入vector中
    for(int i = a.size()-1;i>=0;i--) A.push_back(a[i]-'0'); 
   vector <int> c = div(A,b,r);
    for(int i = c.size()-1;i>=0;i--) cout<<c[i];
    cout<<" "<<r;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45660485/article/details/119295984