`
flyingforce
  • 浏览: 919 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

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[num2.length()];
for (int i = 0; i < num2.length() ; i++) {
char c = num2.charAt(i);
resultStr[i] = multiplyChar(num1, c, num2.length() - i-1);
}
return addStrings(resultStr);
}

private  String multiplyChar(String num, char c, int multiply) {
char newChar[] = new char[num.length()+1  + multiply];
for (int i = 0; i < multiply; i++) {
newChar[newChar.length-1 - i] = '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[i] = (char) ('0' + result % 10);
remain = result / 10;
}
String retStr = new String(newChar);
if (newChar[0] == '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[i].length() > maxLength)
maxLength = a[i].length();
}
char newChar[] = new char[maxLength + 1];
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[j].length() - maxLength + i;
sumAtDigit += getCharInt(a[j], a[j].length() - maxLength + i);
}
newChar[i+1] = (char) (sumAtDigit % 10 + '0');
remain = sumAtDigit / 10;
}
newChar[0]=(char)(remain+'0');
String retStr = new String(newChar);
int removeIndex=0;
   while ((removeIndex < newChar.length) && (newChar[removeIndex++] == '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';
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics