(LeetCode OJ) 43. Multiply Strings
43. Multiply Strings
<a class="pull-right btn btn-default" href="https://leetcode.com/problems/multiply-strings/submissions/" target="_blank">My Submissions</a><button class="btn btn-default active" type="button">Question</button>Total Accepted:51859Total Submissions:231017Difficulty:Medium
Two numbers are given in the form of strings, and the result of multiplication is returned. Note: The result is also a string because the number may be large.
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.
Subscribeto see which companies asked this question
Hide TagsMathStringShow Similar Problems
Analysis:
The code comments are already very detailed. Just simulate the manual calculation.
// Train of thought first: // simulate the manual computing process. class Solution {public: string multiply (string num1, string num2) {int allLen = num1.size () + num2.size (); vector
Tmpresult (allLen, 0); string result (allLen, '0'); // simulate the processing of a manual for (int I = num1.size ()-1; i> = 0; I --) {int n1 = num1 [I]-'0'; for (int j = num2.size ()-1; j> = 0; j --) {int n2 = num2 [j]-'0'; tmpresult [I + j + 1] + = n1 * n2 ;}// carry for (int I = allLen-1; i> 0; I --) {while (tmpresult [I]> 9) {tmpresults [I-1] + = tmpresult [I]/10; tmpresult [I] % = 10 ;}// convert to string for (int I = allLen-1; I> = 0; I --) result [I] = tmpresult [I] + '0'; if (result. find_first_not_of ('0') = string: npos) return "0"; // return result when all 0 is excluded. substr (result. find_first_not_of ('0'), string: npos );}};