面试题35:大数(字符串)相乘
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
1 class Solution { 2 public: 3 string add(string num1, string num2) { 4 string res; 5 char carry = '0'; 6 int n1 = num1.length() - 1; 7 int n2 = num2.length() - 1; 8 char c1, c2; 9 while (n1 >= 0 || n2 >= 0 || carry != '0') { 10 if (n1 < 0) c1 = '0'; 11 else c1 = num1[n1]; 12 if (n2 < 0) c2 = '0'; 13 else c2 = num2[n2]; 14 int sum = c1 - '0' + c2 - '0' + carry - '0'; 15 res.push_back(sum % 10 + '0'); 16 carry = sum / 10 + '0'; 17 n1--; 18 n2--; 19 } 20 reverse(res.begin(), res.end()); 21 return res; 22 } 23 string multiply(string num1, string num2) { 24 int n1 = num1.length() - 1; 25 int n2 = num2.length() - 1; 26 27 string res; 28 for (int i = n1; i >= 0; i--) { 29 string sum; 30 for (int j = n2; j >= 0; j--) { 31 string a = to_string((num1[i] - '0') * (num2[j] - '0')); 32 for (int k = 0; k < n1 + n2 - i - j; k++) { 33 a.push_back('0'); 34 } 35 sum = add(sum, a); 36 } 37 res = add(res, sum); 38 } 39 size_t i = 0; 40 while(i < res.size() && res[i]=='0'){ 41 i++; 42 } 43 if(res.substr(i).empty()) return "0"; 44 return res.substr(i); 45 } 46 };