此文为博主原创题解,转载时请通知博主,并把原文链接放在正文醒目位置。
题目链接 :https://www.luogu.org/problem/show?pid=1581
题目描述
高精度减法
输入输出格式
输入格式:
两个整数a,b(第二个可能比第一个大)
输出格式:
结果(是负数要输出负号)
输入输出样例
输入样例#1:
2 1
输出样例#1:
1
说明
20%数据a,b在long long范围内
100%数据0<a,b<=10的10000次方
AC代码:
1 #include<algorithm> 2 #include<cstring> 3 #include<cstdio> 4 #include<iostream> 5 6 using namespace std; 7 const int MAXN = 10000 + 5; 8 9 struct bign 10 { 11 int len; 12 bool flag; 13 int num[MAXN]; 14 15 bign(){len = 0;flag = false;memset(num,0,sizeof(num));} 16 17 void clear() 18 { 19 len = 0; 20 flag = false; 21 memset(num,0,sizeof(num)); 22 } 23 }ans; 24 25 inline void swap(bign &a,bign &b) 26 { 27 bign tmp; 28 tmp = a; 29 a = b; 30 b = tmp; 31 } 32 33 bool operator < (bign &a,bign &b) 34 { 35 if(a.len < b.len) return true; 36 if(a.len > b.len) return false; 37 int len = a.len; 38 for(int i = 1;i <= len;++ i) 39 { 40 if(a.num[i] > b.num[i]) 41 return false; 42 } 43 return true; 44 } 45 46 bool operator == (bign &a,bign &b) 47 { 48 if(a.len != b.len) return false; 49 for(int i = 1;i <= a.len;++ i) 50 if(a.num[i] != b.num[i]) 51 return false; 52 return true; 53 } 54 55 bign operator - (bign &a,bign &b) 56 { 57 ans.clear(); 58 int len; 59 if(a < b) 60 { 61 ans.flag = true; 62 len = b.len; 63 for(int i = 1;i <= len;++ i) 64 { 65 ans.num[i] += b.num[i] - a.num[i]; 66 if(ans.num[i] < 0) ans.num[i] += 10,ans.num[i+1] --; 67 } 68 } 69 else 70 { 71 ans.flag = false; 72 len = a.len; 73 for(int i = 1;i <= len;++ i) 74 { 75 ans.num[i] += a.num[i] - b.num[i]; 76 if(ans.num[i] < 0) ans.num[i] += 10,ans.num[i+1] --; 77 } 78 } 79 while(!ans.num[len]) len --; 80 ans.len = len; 81 return ans; 82 } 83 84 inline bign get() 85 { 86 ans.clear(); 87 string s; 88 cin>>s; 89 int len = s.length(); 90 for(int i = 0;i < len;++ i) 91 ans.num[len - i] = s[i]-‘0‘; 92 ans.len = len; 93 return ans; 94 } 95 96 inline void print(bign a) 97 { 98 if(a.flag) putchar(‘-‘); 99 int len = a.len; 100 for(int i = len;i >= 1;-- i) 101 printf("%d",a.num[i]); 102 puts(""); 103 } 104 105 int main() 106 { 107 bign a,b; 108 a = get(); 109 b = get(); 110 if(a == b) 111 printf("0\n"); 112 else 113 print(a-b); 114 return 0; 115 }
时间: 2024-10-15 14:54:30