[LeetCode]Multiply Strings

在网上看了一个超级精妙的解法

Multiplication

public class Solution {
    public String multiply(String num1, String num2) {
        int length1 = num1.length();
        int length2 = num2.length();
        int[] record = new int[length1 + length2];
        for (int i = length1 - 1; i >= 0; i--) {
            for (int j = length2 - 1; j >= 0; j--) {
                int tmp = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                int p2 = i + j + 1;
                int p1 = p2 - 1;
                tmp += record[p2];
                record[p2] = tmp % 10;
                record[p1] += (tmp) / 10;
            }
        }
        StringBuffer result = new StringBuffer("");
        for (int i = record.length - 1; i >= 0; i--) {
            result.insert(0, String.valueOf(record[i]));
        }
        String r = String.valueOf(result);
        while(r.length() > 1 && r.startsWith("0")) {
            r = r.substring(1);
        }
        return r;
    }
}

 

posted @ 2015-12-06 06:31  Weizheng_Love_Coding  阅读(141)  评论(0编辑  收藏  举报