大整数减法

样例输入

9999999999999999999999999999999999999
9999999999999

样例输出

9999999999999999999999990000000000000
 1 #include<iostream>
2 #include<cstring>
3 using namespace std;
4 void sub( char *s1, char *s2, char *t )
5 {
6     int len2, len1, k;
7     len2    = strlen( s2 );
8     len1 = strlen( s1 );
9     t[len1]= '\0';
10     len1--;
11     for (int i = len2 - 1; i >= 0; i--, len1-- )
12     {
13         if ( s1[len1] - s2[i] >= 0 )
14             t[len1] = s1[len1] - s2[i] + '0';
15         else{
16             t[len1] = 10 + s1[len1] - s2[i] + '0';
17             s1[len1-1]  = s1[len1 - 1] - 1;
18         }
19     }
20     //s1 -s2 完之后还可能出现s1 还剩头没处理，而且可能减完s2以后出现有 借位
21     k = len1;
22     while ( s1[k] < '0' )
23     {
24         s1[k] += 10;
25         s1[k - 1] -= 1;
26         k--;
27     }
28     //处理完－的以后，直接放s1高位
29     while ( len1 >= 0 )
30     {
31         t[len1] = s1[len1];
32         len1--;
33     }
34     int record;
35     len1 = strlen( s1 );
36     for (int i = 0; i < len1; i++)
37     {
38         if (t[i]!='0')
39         {
40             record=i;
41             break;
42         }
43     }
44     for (int i = record; i < len1; i++)
45     {
46         cout<<t[i];
47     }
48 }
49 int main(){
50     char a[202],b[202],c[202];
51     gets(a);
52     gets(b);
53     sub(a,b,c);
54
55 }

posted @ 2020-04-11 11:45  加微信X466550探讨  阅读(139)  评论(0编辑  收藏  举报