您的位置:首页 > 其它

leetcode 43. Multiply Strings

2016-07-14 10:58 316 查看
//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 static String multiply(String num1, String num2) {
int number1;
int number2;
int carry = 0;													//进位
int temp = 0;													//剩余值
int[] result = new int[num1.length()+num2.length()];
StringBuilder sb = new StringBuilder();							//返回相乘结果的字符串
for(int i = num1.length()-1;i>=0;i--){							//逐位相乘再保存
number1 = num1.charAt(i)-'0';
for(int j = num2.length()-1;j>=0;j--){
number2 = num2.charAt(j)-'0';
result[i+j+1] = result[i+j+1]+number1*number2;
}
}
for(int i = result.length-1;i>=0;i--){							//对结果进行进位或求余
temp = (result[i]+carry)%10;
carry = (result[i]+carry)/10;
result[i] = temp;
}
for(int i = 0;i<result.length;i++){								//将结果加入字符串中
sb.append(result[i]);
}
while(sb.length()>1 && sb.charAt(0) == '0'){					//删除结果中左边的0,只有一个0时则不删除
sb.deleteCharAt(0);
}
return sb.toString();
}

public static void main(String[] args) {
// TODO Auto-generated method stub
String result = multiply("8","7");
System.out.println(result);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: