big number multiplication---straightforward method---not Karatsuba
input: string a, string b
output : a string that denotes a times b
1 #include <string> 2 3 string mul(const string & a, const string & b) { 4 int al = a.length(); 5 int bl = b.length(); 6 int *result = new int[al + bl]; 7 for (int i = 0; i < al + bl; i++) { 8 result[i] = 0; 9 } 10 11 for (int i = 0; i < al; i++) { 12 for (int j = 0; j < bl; j++) { 13 result[i + j + 1] += (a[i] - '0') * (b[j] - '0'); 14 } 15 } 16 for (int i = al + bl - 1; i >= 0; i--) { 17 if (result[i] >= 10) { 18 result[i - 1] += result[i] / 10; 19 result[i] %= 10; 20 } 21 } 22 23 int notZero = 0; 24 while(result[notZero]==0){ 25 ++notZero; 26 } 27 string resultStr = string(al+bl-notZero,'0'); 28 for(int i=notZero;i<al+bl;i++){ 29 resultStr[i-notZero] = result[i]+'0'; 30 } 31 32 delete[] result; 33 34 return resultStr; 35 }
posted on 2013-08-17 11:29 haoyancoder 阅读(184) 评论(0) 收藏 举报
浙公网安备 33010602011771号