// t表示进位,个位没有上级进位,初始值为0 int t = 0; for (int i = 0; i < A.size(); i ++ ) { t += A[i]; // B的长度<A的长度,所以防止越界 if (i < B.size()) t += B[i];
//当前位结果 C.push_back(t % 10);
//计算进位 t /= 10; }
//判断最高位是否有进位,其实可以写进for循环里,看个人习惯 if (t) C.push_back(t); return C; }
intmain() { string a, b; vector<int> A, B; cin >> a >> b; for (int i = a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0'); for (int i = b.size() - 1; i >= 0; i -- ) B.push_back(b[i] - '0');
auto C = add(A, B);
for (int i = C.size() - 1; i >= 0; i -- ) cout << C[i]; cout << endl;
// 判断是否有 A >= B boolcmp(vector<int> &A, vector<int> &B) { // 两数长度不同 if (A.size() != B.size()) return A.size() > B.size();
// 长度相同,从高位开始向低位比较 for (int i = A.size() - 1; i >= 0; i -- ) if (A[i] != B[i]) return A[i] > B[i];
returntrue; }
vector<int> sub(vector<int> &A, vector<int> &B) { vector<int> C; // t表示借位,个位没有上级借位,初始值为0 for (int i = 0, t = 0; i < A.size(); i ++ ) { // 减去低位的借位 t = A[i] - t; if (i < B.size()) t -= B[i]; // 当前数位的结果 C.push_back((t + 10) % 10); // 计算借位 if (t < 0) t = 1; else t = 0; }
intmain() { string a, b; vector<int> A, B; cin >> a >> b; for (int i = a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0'); for (int i = b.size() - 1; i >= 0; i -- ) B.push_back(b[i] - '0');
vector<int> C;
if (cmp(A, B)) C = sub(A, B); else C = sub(B, A), cout << '-';
for (int i = C.size() - 1; i >= 0; i -- ) cout << C[i]; cout << endl;
vector<int> mul(vector<int> &A, int b) { vector<int> C;
int t = 0; // 循环有两个条件 // 1. 大整数 A 各数位均要进行计算 // 2. 大整数各数位计算完,但 t 仍有剩余,则还需要向前进位 ( t != 0 ) for (int i = 0; i < A.size() || t; i ++ ) { if (i < A.size()) t += A[i] * b; C.push_back(t % 10); t /= 10; }
while (C.size() > 1 && C.back() == 0) C.pop_back();
return C; }
intmain() { string a; int b;
cin >> a >> b;
vector<int> A; for (int i = a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0');
auto C = mul(A, b);
for (int i = C.size() - 1; i >= 0; i -- ) printf("%d", C[i]);
string mul(string &a, int b){ string c; int i = a.size() - 1, t = 0; while (i >= 0 || t) { if (i >= 0) t += (a[i-- ] - '0') * b; c.push_back(t % 10 + '0'); t /= 10; }
// A / b ,商是 C ,余数是 r vector<int> div(vector<int> &A, int b, int &r) { vector<int> C; r = 0; // 除法从高位向低位运算 for (int i = A.size() - 1; i >= 0; i -- ) { r = r * 10 + A[i]; C.push_back(r / b); r %= b; } reverse(C.begin(), C.end());