Leetcode: 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.
分析:对于此题,如果按照平时我们算乘法的办法,先将乘数的第一位乘以被乘数,然后第二位乘以被乘数,。。直到乘数的最后一位乘以被乘数,然后把上述结果错位相加。这里有一个规律,被乘数第i位和乘数第j位相乘的结果将加在结果的第i+j和第i+j+1位(模10的余数在第i+j位,进位在第i+j+1位),那么我们可以很方便的实现两个字符串的乘法。代码如下:
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 string result; 5 int n1 = num1.length(), n2 = num2.length(); 6 if(n1 == 0 || n2 == 0) return result; 7 8 vector<int> res(n1+n2, 0);//use vector stores multiply result 9 reverse(num1.begin(), num1.end());//reverse string 10 reverse(num2.begin(), num2.end()); 11 12 for(int i = 0; i < n1; i++){ 13 int v1 = num1[i] - '0'; 14 for(int j = 0; j < n2; j++){ 15 int v2 = num2[j] - '0'; 16 res[i+j] += v1*v2; 17 res[i+j+1] += res[i+j]/10; 18 res[i+j] %= 10; 19 } 20 } 21 22 transform(find_if(res.rbegin(), prev(res.rend()), [](int i){return i > 0;}),res.rend(), back_inserter(result), [](int i){return i + '0';});//transform each int in vector<int> to char, also remove preceding zeroes but the last zero 23 return result; 24 } 25 };
transform函数的运用使代码行数更少,find_if(res.begin(), prev(res.rend()), [](int i){return i > 0;})除去结果中的preceding zeroes同时由于使用prev(res.rend())保护了只有一个0的情况。