Monday, April 25, 2016

[LeetCode] 43. 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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.



public class Solution {


    public String multiply(String num1, String num2) {
        
        String ret = new String();
        int len1 = num1.length();
        int len2 = num2.length();
        if(0 == len1 || 0 == len2)
            return ret;
        
        String rNum1 = new StringBuffer(num1).reverse().toString();
        String rNum2 = new StringBuffer(num2).reverse().toString();
        
        // At first, was trying to store everything in string operation as well. Quite complicated.
        int[] res = new int[len1 + len2 + 1];
        
        for(int i = 0; i != len2; ++i){
            
            int vi = rNum2.charAt(i) - '0';
            
            for(int j = 0; j != len1; ++j){
                
                res[i+j] += (rNum1.charAt(j) - '0') * vi;
                
            }
            
        }
        
        int carry = 0;
        
        for(int k = 0; k != len1 + len2 +1; ++k){
            
            res[k] += carry;
            carry = res[k] / 10;
            res[k] = res[k] % 10;

        }
        
        StringBuilder sb = new StringBuilder();
        
        int k = len1 + len2;
        
        while(k >=0){
            if(0 == res[k])
                --k;
            else
                break;
        }
        
        while(k >= 0){
            sb.append(res[k--]);
        }
        
        if(sb.toString().isEmpty()){
            return new String("0");
        }
        
        return sb.toString();
        
    }
}

No comments:

Post a Comment