【LeetCode】43. Multiply Strings
Multiply Strings
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.
class Solution { public: string multiply(string num1, string num2) { int n1 = num1.size(); int n2 = num2.size(); vector<int> result(n1+n2); string resultStr; for(int i = n1-1; i >= 0; i --) {// for num1[i] int carry = 0; int val1 = num1[i] - '0'; for(int j = n2-1; j >= 0; j --) {// for num2[j] int val2 = num2[j] - '0'; int res = val1 * val2; int ind = (n1-1-i)+(n2-1-j); result[ind] += carry; result[ind] += res; carry = result[ind] / 10; result[ind] %= 10; } if(carry != 0) { int ind = (n1-1-i)+n2; result[ind] += carry; } } //reverse result reverse(result.begin(), result.end()); int i; for(i = 0; i < n1+n2; i ++) { if(result[i] != 0) break; } if(i == n1+n2) //all 0 return "0"; else { for(; i < n1+n2; i ++) { resultStr += (result[i] + '0'); } return resultStr; } } };