码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Multiply Strings

时间:2015-12-06 07:26:04      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

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;
    }
}

 

[LeetCode]Multiply Strings

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5022842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!