0
点赞
收藏
分享

微信扫一扫

43. Multiply Strings


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.

class Solution {
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] pos = new int[m + n]; // 0是最高位

for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
// p1代表进位, p2表示本位。
int p1 = i + j, p2 = i + j + 1;
// sum 就是本位的乘积加上本位已有的值。
int sum = mul + pos[p2];
// 进位就是除以10的余数
pos[p1] += sum / 10;
// 本位就是剩下的个位数。
pos[p2] = (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();
}
}

class Solution {
public String multiply(String num1, String num2) {
int firstLength = num1.length();
int secondLength = num2.length();
StringBuilder sb = new StringBuilder();
int[] resArr = new int[firstLength + secondLength];
for(int i= firstLength-1; i>=0; i-- ){
for(int j= secondLength-1; j>=0; j-- ){
int temp = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
temp += resArr[i+j+1];
resArr[i+j+1] = temp%10;
resArr[i+j] += temp/10;
}
}
boolean nonZeroFound = false;
for(int i : resArr){
if(i != 0) nonZeroFound = true;
if(nonZeroFound) sb.append(i);
}
if(!nonZeroFound) sb.append("0");
return sb.toString();
}
}


举报

相关推荐

0 条评论