Luo Gu P2142 high-precision subtraction problem solution

Looking for the original title, please click here: Portal

Original title:

Title Description
High-precision subtraction

Input Format
Two integers a, b (a second possible larger than the first)

Output Format
Result (the output is negative to negative sign)

Sample input and output
Enter Copy
2
1
Copy Output
1 
Description / Tip
 20 is % of the data a, long in the long range b

100 % Data 0 <a, b <10 ^ 10086 ( where ^ is a power)

It is easier to talk about the principle of high-precision operations.

Why produce high-precision arithmetic?

Since c ++ data structures are very strict, but the number of data structures stored in c ++ provided only int and long long, when stored data when the operation of the two data types through the Metropolitan cause overflow.

So precision was born!

Precision about the process:

1. The two numbers to be subjected to calculation of a specific string stored Situation

2. The string stored from the lowest number to the highest bit (MSB highest) stored sequentially up with an int

3. operation

4. Each of the carry and the most significant bit update

5. Remove the leading zero

 

Then the code is as follows:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #define N 10087
 5 using namespace std;
 6 char a[N];
 7 char b[N];
 8 char ta[N];
 9 char ans[N];
10 int aa[N],bb[N],ansa[N];
11 int tb;
12 bool flag;
13 int main()
14 {
15     scanf("%s",&a);
16     scanf("%s",&b);
17     int la=strlen(a),lb=strlen(b);
18     if(lb>la) {
19         flag=true;
20         strcpy(ta,a);strcpy(a,b);strcpy(b,ta);
21         tb=la;la=lb;lb=tb;
22     }
23     else{
24         if(la==lb){
25             for(int i=0;i<la;i++){
26                 if(a[i]==b[i]){
27                     continue;
28                 }
29                 if(a[i]>b[i]){
30                     break;
31                 }
32                 flag=true;
33                 strcpy(ta,a);strcpy(a,b);strcpy(b,ta);
34                 tb=la;la=lb;lb=tb;
35                 break;
36             }
37         }
38     }
39     for(int i=1;i<=la;i++){
40         aa[i]=a[la-i]-'0';
41     }
42     for(int i=1;i<=lb;i++){
43         bb[i]=b[lb-i]-'0';
44     }
45     int mm=max(la,lb);
46     for(int i=1;i<=mm;i++){
47         ansa[i]+=(aa[i]-bb[i]);
48         if(ansa[i]<0){
49             ansa[i]+=10;
50             ansa[i+1]--;
51         }
52     }
53     for(int i=mm;i>=2;i--){
54         if(ansa[i]){
55             break;
56         }
57         mm--;
58     }    
59     if(flag) printf("-");
60     for(int i=mm;i>=1;i--){
61         printf("%d",ansa[i]);
62     }
63     return 0;
64 }

 

Guess you like

Origin www.cnblogs.com/robertspot/p/12375979.html