您的位置:首页 > 其它

LeetCode力扣之 Multiply Strings

2018-03-07 20:51 471 查看
Given two non-negative integers 
num1
 and 
num2
 represented as strings, return the product of 
num1
 and 
num2
.Note:The length of both 
num1
 and 
num2
 is < 110.
Both 
num1
 and 
num2
 contains only digits 
0-9
.
Both 
num1
 and 
num2
 does not contain any leading zero.

You must not use any built-in BigInteger library or convert the inputs to integer directly.
/**
* Created by lxw, liwei4939@126.com on 2018/3/7.
*/
public class L043_Multiply_String {

public String multiply(String num1, String num2) {

int
4000
len1 = num1.length();
int len2 = num2.length();
int[] pos = new int[len1 + len2];

for (int i = len1 - 1; i >= 0; i--){
for (int j = len2 - 1; j >= 0; j--){
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int pos1 = i + j, pos2 = i + j + 1;
int sum = mul + pos[pos2];

pos[pos1] += sum / 10;
pos[pos2] = sum % 10;
}
}
StringBuilder sb = new StringBuilder();
for (int p : pos){
if (!(sb.length() == 0 && p == 0)){
sb.append(p);
}
}

return sb.length() == 0 ? "0" :sb.toString();
}

public static void main(String[] args){
String num1 = "25";
String num2 = "8";

L043_Multiply_String tmp = new L043_Multiply_String();
System.out.println(tmp.multiply(num1, num2));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: