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.
Subscribe to see which companies asked this question
这个我写的有点麻烦了,可以不用一位一位加的,完全可以把几位当乘法算
public class Solution {
private String deal(String x){
int i = 0;
while(i<x.length()-1&&x.charAt(i)=='0'){
i++;
}
return x.substring(i,x.length());
}
private String add(String n1,String n2){
if(n1.length()<n2.length()){
String tem = n1;
n1=n2;
n2=tem;
}
int add=0;
int i = n1.length()-1;
int j = n2.length()-1;
String ret = "";
while(j>=0){
int r = n1.charAt(i)+n2.charAt(j)-2*'0'+add;
if(r>=10){
r-=10;
add=1;
}else{
add=0;
}
ret=(char)(r+'0')+ret;
i--;
j--;
}
while(i>=0){
int r = n1.charAt(i)-'0'+add;
if(r>=10){
r-=10;
add=1;
}else{
add=0;
}
ret=(char)(r+'0')+ret;
i--;
j--;
}
if(add==1)ret='1'+ret;
return ret;
}
private String mulSingle(String nums,char n){
String ret = "";
if(n==0)return "0";
int k = n-'0';
int add = 0;
int i = nums.length()-1;
while(i>=0){
int r = (nums.charAt(i)-'0')*k+add;
if(r>=10){
add=r/10;
r=r%10;
}else{
add=0;
}
ret=(char)(r+'0')+ret;
i--;
}
if(add!=0)ret=(char)(add+'0')+ret;
return ret;
}
public String multiply(String num1, String num2) {
if(num1.length()<1||num2.length()<1)return "0";
String ret = "0";
int i = num2.length()-1;
while(i>=0){
String s = mulSingle(num1,num2.charAt(i));
int j = num2.length()-1-i;
while(j>0){
s=s+'0';
j--;
}
ret=add(ret,s);
i--;
}
return deal(ret);
}
}