Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created June 29, 2013 02:53
Show Gist options
  • Save luoxiaoxun/5889486 to your computer and use it in GitHub Desktop.
Save luoxiaoxun/5889486 to your computer and use it in GitHub Desktop.
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.
C++:
class Solution {
public:
string multiply(string num1, string num2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(num1.size()==0||num2.size()==0) return "";
string ret(num1.size()+num2.size()+1,'0');
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
for(int i=0;i<num2.size();i++){
int dig2=num2[i]-'0';
int carry=0;
for(int j=0;j<num1.size();j++){
int dig1=num1[j]-'0';
int temp=ret[i+j]-'0';
int cur=dig1*dig2+temp+carry;
ret[i+j]=cur%10+'0';
carry=cur/10;
}
ret[i+num1.size()]=carry+'0';
}
reverse(ret.begin(),ret.end());
int pos=ret.find_first_not_of('0',0);
if(pos<0||pos>=ret.size())
pos=ret.size()-1;
return ret.substr(pos,ret.size()-pos);
}
};
Java:
public class Solution {
public String multiply(String num1, String num2) {
// Start typing your Java solution below
// DO NOT write main() function
if(num1.length()==0||num2.length()==0) return "";
if(num1.equals("0")||num2.equals("0")) return "0";
char[] c1=new StringBuilder(num1).reverse().toString().toCharArray();
char[] c2=new StringBuilder(num2).reverse().toString().toCharArray();
char[] c=new char[c1.length+c2.length+1];
Arrays.fill(c,'0');
for(int i=0;i<c2.length;i++){
int dig2=c2[i]-'0';
int carry=0;
for(int j=0;j<c1.length;j++){
int dig1=c1[j]-'0';
int temp=c[i+j]-'0';
int cur=dig1*dig2+temp+carry;
c[i+j]=(char) (cur%10+'0');
carry=cur/10;
}
c[i+c1.length]=(char) (carry+'0');
}
String ret=new StringBuilder(new String(c)).reverse().toString();
int pos=0;
while(ret.charAt(pos)=='0'&&pos<ret.length()) pos++;
return ret.substring(pos);
}
}
@shivendra096
Copy link

Thanks :) Works Perfect

@anidub
Copy link

anidub commented May 10, 2017

what is the time complexity ?

@slahmer97
Copy link

the Time Complexity is O(m*n) where n=Len(Str1),m=Len(Str2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment