大整数加法
/* 大整数加法 调用方式:add(a, b); 返回类型:string */ string add(string a, string b) { string s; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int i = 0; int m, k = 0; while(a[i] && b[i]) { m = a[i] - '0' + b[i] - '0' + k; k = m / 10; s += (m % 10 + '0'); i++; } if(i == a.size()) { while(i != b.size()) { m = k + b[i] - '0'; k = m / 10; s += m % 10 + '0'; i++; } if(k) s += k + '0'; } else if(i == b.size()) { while(i != a.size()) { m = k + a[i] - '0'; k = m / 10; s += m % 10 + '0'; i++; } if(k) s += k + '0'; } reverse(s.begin(), s.end()); return s; }
大整数减法:
/* 大整数减法 */ #include<cstdio> #include<cstring> #include<string> #include<iostream> using namespace std; string sub(string a, string b) { int i, j, k, s, flag = 1; int tmpa[10000], tmpb[10000], c[10000]; string ans; if(a.size() < b.size() || (a.size() == b.size() && a.compare(b) < 0)) { string tmp = a; a = b; b = tmp; flag = 0; } while(a.length() > b.length()) b = '0' + b; int len = a.length(); for(i = 0; i < len; i++) { tmpa[i] = a[i] - '0'; tmpb[i] = b[i] - '0'; } for(i = len - 1; i >= 0; i--) { if(tmpa[i] >= tmpb[i]) c[i] = tmpa[i] - tmpb[i]; else { c[i] = 10 + tmpa[i] - tmpb[i]; tmpa[i-1]--; } } for(i = 0; i < len - 1; i++) if(c[i] != 0) break; for(j = i; j < len; j++) ans = ans + (char)(c[j] + '0'); if(!flag) ans = '-' + ans; return ans; } int main() { string a, b; while(cin >> a >> b) { cout << sub(a, b) << endl; } return 0; }
大数运算模板
时间: 2024-10-09 17:55:49