Simple && clear java solution


  • 12
    C
    public class Solution {
        public String multiply(String num1, String num2) {
            int len1 = num1.length();
            int len2 = num2.length();
            int len = len1 + len2;
            int[] mul = new int[len];
            for (int i = len1 - 1; i >= 0; i--) {
                int a = num1.charAt(i) - '0';
                int k = len2 + i;
                for (int j = len2 - 1; j >= 0; j--) {
                    int b = num2.charAt(j) - '0';
                    int c = mul[k] + a * b;
                    mul[k] = c % 10;
                    mul[k - 1] = mul[k - 1] + c /10;
                    k--;
                }
            }
            int i = 0;
            while(mul[i] == 0 && i < len - 1)  i++;
            StringBuilder sb = new StringBuilder();
            for (; i < len; i++)
                sb.append(mul[i]);
            return sb.length() == 0 ? "0" : sb.toString();
        }
    }

  • -6
    W

    public static String multiply(String num1,String num2){
    String result = "";
    int len1 = num1.length();
    int len2 = num2.length();
    int len = len1 + len2;
    int[] num = new int[len];
    int trade = 0;
    for(int k=len-2;k>=0;k--){
    int res = 0;
    for(int i=len1-1;i>=0;i--){
    for(int j=len2-1;j>=0;j--){
    if(i + j == k){
    res += Integer.valueOf(num1.charAt(i) - '0') * Integer.valueOf(num2.charAt(j) - '0');
    }
    if(i == 0 && j == 0){
    res += trade;
    trade = res / 10;
    num[k+1] = res % 10;
    }
    }
    }
    }
    if(trade != 0){
    result = trade + result;
    for(int j=1;j<len;j++){
    result += num[j];
    }
    }else{
    int i = 1;
    while(i<len && num[i] == 0){
    i++;
    }
    if(i == len){
    result = "0";
    }
    for(int j=i;j<len;j++){
    result += num[j];
    }
    }
    return result;
    }


  • 0
    B

    Great solution. I have one more suggestion. We can check if(a != 0) before we enter into the nested for loop.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.