计算 a * b
时间复杂度为 O(n^2)
代码:
1 #include <iostream> 2 using namespace std; 3 4 const int MAXN = 1e4; 5 int a[MAXN], b[MAXN], sol[MAXN], lena, lenb; 6 7 void solve(void){ 8 int cnt = 0, indx = MAXN - 1; 9 for(int i = lenb - 1; i >= 0; i--){ 10 int pos = indx--; 11 for(int j = lena - 1; j >= 0; j--){ 12 int cc = b[i] * a[j] + cnt + sol[pos]; 13 sol[pos--] = cc % 10; 14 cnt = cc / 10; 15 } 16 sol[pos] += cnt; 17 cnt = 0; 18 } 19 } 20 21 int main(void){ 22 string s1, s2; 23 cin >> s1 >> s2; 24 lena = s1.size(); 25 lenb = s2.size(); 26 for(int i = 0; i < lena; i++){ 27 a[i] = s1[i] - '0'; 28 } 29 for(int i = 0; i < lenb; i++){ 30 b[i] = s2[i] - '0'; 31 } 32 solve(); 33 int i = 0; 34 while(sol[i] == 0) i++; 35 while(i < MAXN) cout << sol[i++]; 36 cout << endl; 37 return 0; 38 }