首页 > 其他 > 详细

leetcode--Multiply Strings

时间:2014-03-20 21:27:28      阅读:404      评论:0      收藏:0      [点我收藏+]

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.

 

Have you been asked this question in an interview? 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
    public String multiply(String num1, String num2) {
        int len1 = num1.length(), len2 = num2.length();
        //using an array to save the result of multiply and initialized as zeros
        int[] mult = new int[len1 + len2 + 1];
        for(int i = 0; i < len1 + len2 + 1; ++i)
            mult[i] = 0;
 
        for(int j = 0; j < len1; ++j){
            int carry = 0;
            int singledigit = num1.charAt(len1 - 1 - j) - ‘0‘;
            if(singledigit != 0){
                for(int k = 0; k < len2; ++k){
                    int product = (num2.charAt(len2 - 1 - k)-‘0‘) * singledigit + carry
                        + mult[len1 + len2 - j - k];
                    mult[len1 + len2 -j - k] = product % 10;
                    carry = product / 10;                    
                }
                if(carry != 0)
                    mult[len1 - j] = carry;
            }           
        }
        StringBuffer sbf = new StringBuffer();
        int start = 0;
        while((start < len1 + len2 + 1) && mult[start] == 0)
            ++start;       
        if(start < len1 + len2 + 1){   
            for(int i = start; i < len1 + len2 + 1; ++i)
                sbf.append(mult[i]);
        }
        else
            sbf.append(‘0‘);
        return sbf.toString();
    }
}

  

leetcode--Multiply Strings,布布扣,bubuko.com

leetcode--Multiply Strings

原文:http://www.cnblogs.com/averillzheng/p/3612664.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!