2014年3月14日星期五

LeetCoder - 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) {
        int[] arr = new int[num1.length() + num2.length()];
        for (int i = num1.length() - 1; i >= 0; i--) {
            for (int j = num2.length() - 1; j >= 0; j--) {
                int n1 = num1.charAt(i) - '0';
                int n2 = num2.charAt(j) - '0';
                arr[i + j + 1] += n1 * n2;
            }
        }
        int carry = 0;
        for (int i = arr.length - 1; i >= 0; i--) {
            int val = carry + arr[i];
            carry = val / 10;
            val = val % 10;
            arr[i] = val;
        }
        StringBuilder sb = new StringBuilder();
        boolean notZero = false;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 0 && !notZero) {
                continue;
            } else {
                notZero = true;
                sb.append(arr[i]);
            }
        }
        if (sb.length() == 0) return "0";
        else return sb.toString();
    }
}

没有评论:

发表评论