leetcode--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.

 

Have you been asked this question in an interview? 

 

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

  

posted @ 2014-03-19 23:58  Averill Zheng  阅读(131)  评论(0编辑  收藏  举报