PAT (Basic Level) Practice 1017 A除以B (20分) (大数除法+大神简洁20行代码)

1.题目

本题要求计算 A/B,其中 A 是不超过 1000 位的正整数,B 是 1 位正整数。你需要输出商数 Q 和余数 R,使得 A=B×Q+R 成立。

输入格式:

输入在一行中依次给出 A 和 B,中间以 1 空格分隔。

输出格式:

在一行中依次输出 Q 和 R,中间以 1 空格分隔。

输入样例:

123456789050987654321 7

输出样例:

17636684150141093474 3

2.代码

 我的

#include<iostream>
#include<string>
using namespace std;
int main()
{

		char number[1000];
		int number3[1000] ;
		int number4[1000] ;
		int i = 0;
		int number2 = 0;
		int temp = 0;
		int flag = 0;
		int flag2 = 0;
		cin >> number>>number2;
		for (i = 0; number[i]!='\0'; i++)
		{
			number3[i] = number[i] - '0';
			flag++;
		}
		int count = 0;
		int count2 = 0;
		for (i = 0; i<flag; i++)
		{
			if (number3[count] >= number2)
			{
				temp = number3[count] / number2;
				if (number3[count] != number2)
				{
					number4[count2] = temp; count2++;
					number3[count] = number3[count] % number2;
				}
				else
				{
					number4[count2] = temp; count2++;
					count++;
					while (number3[count] == 0) {
				
						if (count == flag-1)
							break;
						count++;
						number4[count2] = 0;
						count2++;
						
					}

				}

			}
			else
			{
				if (count == flag - 1)
				{
					if (number3[count - 1] >= number2)
					{
						number4[count2] = 0; count2++;
					}
					break;
				}
				temp = (number3[count] * 10 + number3[count + 1]) / number2;
				number4[count2] = temp; count2++;
				number3[count + 1] = (number3[count] * 10 + number3[count + 1]) % number2;
				count++;
			}

		}
		for (i = 0; i < count2; i++)
			cout << number4[i];
		cout << " " << number3[count];

	}

大神的(参见https://www.cnblogs.com/pgzhang/p/9501862.html

#include<iostream>
#include<string>
using namespace std;

int main() {
    string s;
    int d,div,mod;
    cin >> s>>d;
    int len = s.length();
    div = (s[0] - '0') / d;
    mod = (s[0] - '0') % d;
    if ( div != 0 || len == 1) 
        cout << div;    
    for (int i = 1; i < len; i++) {
        div = (mod * 10 + (s[i] - '0')) / d;
        cout << div;
        mod = (mod * 10 + (s[i] - '0')) % d;
    }
    cout << ' ' << mod << endl;
    return 0;
}

 

posted @ 2020-02-14 13:01  Jason66661010  阅读(103)  评论(0编辑  收藏  举报