LeetCode 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.
这道题可花了时间,还是对位置有点控制不好。
public class Solution { public String multiply(String num1, String num2) { String resultStr = new String; for (int i = 0; i < num2.length() ; i++) { char c = num2.charAt(i); resultStr* = multiplyChar(num1, c, num2.length() - i-1); } return addStrings(resultStr); }
private String multiplyChar(String num, char c, int multiply) {
char newChar = new char;
for (int i = 0; i < multiply; i++) {
newChar = '0';
}
int remain = 0;
for (int i = newChar.length - multiply-1; i >= 0; i--) {
int numChar = getCharInt(num, num.length() - newChar.length + multiply + i);
int result = numChar * (c - '0') + remain;
newChar* = (char) ('0' + result % 10);
remain = result / 10;
}
String retStr = new String(newChar);
if (newChar == '0')
return retStr.substring(1, retStr.length());
return retStr;
}
private String addStrings(String a) {
int maxLength = 0;
for (int i = 0; i < a.length; i++) {
if (a*.length() > maxLength)
maxLength = a*.length();
}
char newChar = new char;
boolean removeHead = false;
int remain = 0;
for (int i = maxLength-1; i >= 0; i--) {
int sumAtDigit = remain;
for (int j = 0; j < a.length; j++) {
int tmpIndex = a.length() - maxLength + i;
sumAtDigit += getCharInt(a, a.length() - maxLength + i);
}
newChar = (char) (sumAtDigit % 10 + '0');
remain = sumAtDigit / 10;
}
newChar=(char)(remain+'0');
String retStr = new String(newChar);
int removeIndex=0;
while ((removeIndex < newChar.length) && (newChar == '0'));
if (removeIndex > 0) {
retStr = retStr.substring(removeIndex-1, retStr.length());
}
return retStr;
}
private int getCharInt(String a, int index) {
if (index < 0)
return 0;
if (index > a.length()-1)
return 0;
return a.charAt(index) - '0';
}
}