Concise Java Solution


  • 0
    S
    public class Solution {
        public String multiply(String num1, String num2) {
            char[] array1 = num1.toCharArray();
            char[] array2 = num2.toCharArray();
            int m = array1.length;
            int n = array2.length;
            int[] sums = new int[m + n];
            for (int i = n - 1; i >= 0; i--) {
                int lowVal = array2[i] - '0';
                int carry = 0;
                for (int j = m - 1; j >= 0; j--) {
                    int upVal = array1[j] - '0';
                    int pro = lowVal * upVal;
                    int sum = pro + sums[i + j + 1] + carry;
                    sums[i + j + 1] = sum % 10;
                    carry = sum / 10;
                }
                if (carry != 0) sums[i] = carry;
            }
            StringBuilder sb = new StringBuilder();
            for (int num : sums) sb.append(num);
            while (sb.length() > 1 && sb.charAt(0) == '0') sb.deleteCharAt(0);
            return sb.toString();
        }
    }
    

Log in to reply
 

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