Created
June 23, 2019 21:20
-
-
Save adamkorg/1d83d0f6eb273b2545e745196c8924d1 to your computer and use it in GitHub Desktop.
Leetcode 43: Multiply Strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
string multiply(string num1, string num2) { | |
if (num1.size() < num2.size()) | |
swap(num1, num2); | |
vector<string> a; | |
for (int i=num2.size()-1; i>=0; i--) { | |
string sum(num1.size()+num2.size(), '0'); | |
int carry=0, j=0; | |
for (j=num1.size()-1; j>=0; j--) { | |
int digit = (num2[i]-'0')*(num1[j]-'0'); | |
digit += carry; | |
int pos = (num2.size()-i-1)+(num1.size()-j-1); | |
sum[sum.size()-pos-1] = '0'+(digit%10); | |
carry = (digit/10); | |
} | |
if (carry>0) { | |
int pos = num1.size()+(num2.size()-i); //pos from right | |
sum[sum.size()-pos] = carry + '0'; | |
} | |
a.push_back(sum); | |
} | |
//now add all the string numbers in array a | |
string result(num1.size() + num2.size(), '0'); | |
int carry = 0; | |
for (int i=result.size()-1; i>=0; i--) { | |
int digit = carry; | |
for (int j=0; j<a.size(); j++) | |
digit += a[j][i] - '0'; | |
result[i] = (digit % 10) + '0'; | |
carry = digit / 10; | |
} | |
//strip out leading zeros | |
int start = 0; | |
for ( ; start < result.size()-1 && result[start]=='0'; start++) {} | |
return result.substr(start); | |
} | |
int main() { | |
string num1 = "999", num2 = "999"; | |
cout << multiply(num1, num2) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment