原题网址:https://leetcode.com/problems/multiply-strings/
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.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
方法:模拟乘法运算。
public class Solution {
public String multiply(String num1, String num2) {
int[] n1 = new int[num1.length()];
int[] n2 = new int[num2.length()];
int[] m = new int[num1.length() + num2.length()];
for(int i=0; i<n1.length; i++) {
n1[n1.length-1-i] = num1.charAt(i)-'0';
}
for(int i=0; i<n2.length; i++) {
n2[n2.length-1-i] = num2.charAt(i)-'0';
}
for(int i=0; i<n1.length; i++) {
int carry = 0;
for(int j=0; j<n2.length; j++) {
int mul = m[i+j] + n1[i]*n2[j] + carry;
m[i+j] = mul % 10;
carry = mul / 10;
}
if (carry > 0) m[i+n2.length] += carry;
}
boolean notZero = false;
StringBuilder sb = new StringBuilder();
for(int i=m.length-1; i>=0; i--) {
if (m[i] > 0) notZero = true;
if (notZero) sb.append(m[i]);
}
if (!notZero) sb.append(0);
return sb.toString();
}
}