leetcode - Multiply Strings
2013-12-10 18:19 张汉生 阅读(128) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 int len1 = num1.length(); 7 int len2 = num2.length(); 8 if (len1<=0 || len2<=0) 9 return ""; 10 int * a = new int[len1]; 11 int * b = new int[len2]; 12 for (int i=0; i<len1; i++) 13 a[len1-i-1] = num1.at(i)-'0'; 14 for (int i=0; i<len2; i++) 15 b[len2-i-1] = num2.at(i)-'0'; 16 int * c = new int[len1+len2]; 17 for (int i=0; i<len1+len2; i++){ 18 c[i] = 0; 19 } 20 for (int i=0; i<len1; i++) 21 for (int j=0; j<len2; j++) 22 c[i+j] += a[i] *b[j]; 23 for (int i=0; i<len1+len2-1; i++){ 24 if (c[i]>=10){ 25 c[i+1] += c[i]/10; 26 c[i] %= 10; 27 } 28 } 29 string rlt = ""; 30 bool flag = false; 31 for (int i=len1+len2-1; i>=0; i--){ 32 if (c[i]!=0) 33 flag = true; 34 if (flag) 35 rlt += (char)('0'+c[i]); 36 } 37 delete []a; 38 delete []b; 39 delete []c; 40 if (rlt=="") 41 rlt = "0"; 42 return rlt; 43 } 44 };