代码:
- class Solution {
- public String multiply(String num1, String num2) {
- if(num1.equals("0")||num2.equals("0"))return "0";
- int i,j;
- String res = "0";
- for(i = num2.length()-1;i>=0;i--){
- StringBuilder curr = new StringBuilder();
- int f = 0;
- for(int k = num2.length()-1;k>i;k--){
- curr.append(0);
- }
- int y = num2.charAt(i) - '0';
- for(j = num1.length()-1;j>=0;j--){
- int x = num1.charAt(j) - '0';
- int product = x * y + f;
- curr.append(product%10);
- f = product /10;
- }
- if(f!=0)curr.append(f);
- res = addStrings(res,curr.reverse().toString());
- }
- return res;
- }
- public String addStrings(String num1, String num2) {
- StringBuilder res = new StringBuilder();
- int f = 0;
- int i,j;
- for(i=num1.length()-1,j=num2.length()-1;i>=0||j>=0;i--,j--){
- int x = i>=0? num1.charAt(i)-'0' : 0;
- int y = j>=0? num2.charAt(j)-'0' : 0;
- int curNum = x + y + f;
- if(curNum<=9){
- f = 0;
- res.append(curNum);
- }else{
- f = 1;
- res.append(curNum - 10);
- }
- }
- if(f==1) res.append(1);
- res.reverse();
- return res.toString();
- }
- }