#include<iostream> #include<string> using namespace std; const int Max = 550; void Enlarge(int p[], int q[], int bits); //将数组p的数字串右移bits位 int Compare(int a[], int b[]); //比较大小 void Subtract(int a[], int b[]); //数组减法 int main() { int a[Max] = {0}, b[Max] = {0}, c[Max] = {0}; string str1, str2; cin >> str1 >> str2; int len1 = str1.size(), len2 = str2.size(), len = len1 - len2 + 1, i; a[0] = len1; b[0] = len2; c[0] = len; for (i = 1; i <= len1; i ++) a[i] = str1[len1 - i] - '0'; for (i = 1; i <= len2; i ++) b[i] = str2[len2 - i] - '0'; if (Compare(a, b) == -1) cout << "0"; else { for (i = c[0]; i > 0; i --) { int t[Max] = {0}; Enlarge(b, t, i); while( Compare(a, t) >= 0) { c[i] ++; Subtract(a, t); } } while(c[0] > 0 && c[c[0]] == 0) c[0] --; for (i = c[0]; i > 0; i --) cout << c[i]; } return 0; } void Enlarge(int p[], int q[], int bits) { for (int i = 1; i <= p[0]; i ++) q[i + bits - 1] = p[i]; q[0] = p[0] + bits - 1; //q[0]存储的数字串的位置 } int Compare(int a[], int b[]) { int i; if (a[0] > b[0]) //a的位数 > b的位数, 则a > b return 1; else if (a[0] < b[0]) //a的位数 < b的位数, 则a < b return -1; for (i = a[0]; i > 0; i --) { if (a[i] > b[i]) return 1; else if (a[i] < b[i]) return -1; } return 0; // 两数相等 } void Subtract(int a[], int b[]) { int flag , i; flag = Compare(a, b); if (flag == 0) a[0] = 0; else if (flag == 1) { for (i =1; i <= a[0]; i ++) { a[i] = a[i] - b[i]; if (a[i] < 0) { a[i] += 10; a[i + 1] --; } } while(a[0] > 0 && a[a[0]] == 0) //去掉高位多余的0,同时修正a的位数 a[0] --; } }
参考https://blog.csdn.net/chuanzhouxiao/article/list/2博主的文章