PAT - Grade B 1017 A divided by B (analog division vertical)

1017. A divided by B (20)

time limit
100 ms
memory limit
65536 kB
code length limit
8000 B
Judgment procedure
Standard
author
CHEN, Yue

This problem requires the calculation of A/B, where A is a positive integer with no more than 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 in 1 line, separated by 1 space.

Output format:

Output Q and R sequentially in 1 line, separated by 1 space.

Input sample:
123456789050987654321 7
Sample output:
17636684150141093474 3

Idea: Simulate the vertical division of the division The i-digit number formed by the first i numbers takes the remainder of the b division quotient, 

#include<cstdio>
#include<cstring>
using namespace std;

int main(){
	char arr[1005];
	int b, x = 0, flag = 0;
	scanf("%s %d", arr, &b);
	int len ​​= strlen(arr);
	if(len == 1 && arr[0] - '0' < b) printf("0 %c", arr[0]); // prevent a number less than b
	else{
		for(int i = 0; i < len; i++){
			x = x * 10 + arr[i] - '0';
			if(x < b){
				if(flag) printf("0"); // don't print 0 if no number has been output
			}else{
				if(!flag) flag = 1; //prevent 0 from appearing in front
				printf("%d", x / b);
				x = x % b;
			}
		}
		printf(" %d", x);
	}
	return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325757139&siteId=291194637