[leedcode 43] Multiply Strings

Straight forward idea. Just like the way we multiply numbers. Don't forget considering the carry and be careful. e.g.

  123*456,
what we usually do is:
      123
*    456
-----------
      738
    615
+492
-----------
  56088
thus, 123*456 = 56088.
In the same way, the algorithm is:

from end to start position, use a new array to store temproary digit.
A*B
(1)For each element B[i]
    Compute tmp = B[i]*A
    Add tmp to the previous result, note the start position. res = res"+"tmp
(2)Return result.

To be specific,
(1) char2int,     int(char-'0');
(2) int2char,     char(int+'0')
(3) Don't forget the carry in each add or multiply operation.
(4) Don't forget the carry after last operation. e.g.  82+33 = 115.
(5) Be careful with the string order and the number order.

public class Solution {
    public String multiply(String num1, String num2) {
        //用字符串模拟乘法,注意事项见上面分析。注意result的第0位是结果的个位
        
        int len1=num1.length();
        int len2=num2.length();
        int[] result=new int[len1+len2];
        int carry=0;
        int i=0;
        int j=0;
        for( i=0;i<len2;i++){
            int n2=num2.charAt(len2-1-i)-'0';
            carry=0;
            for(j=0;j<len1;j++){
                result[i+j]+=n2*(num1.charAt(len1-1-j)-'0')+carry;
                
                carry=result[i+j]/10;
                result[i+j]%=10;
            }
            result[i+j]=result[i+j]+carry;
        }
        i=len1+len2-1;
        while(i>0){
            if(result[i]!=0)
                break;
            i--;
        }
        StringBuilder res=new StringBuilder();
        int k=i;
        while(k>=0){
            res.append((char)(result[k]+'0'));//res.append(result[k]+'0');会得整数,比如result[k]为0时,添加的是48
            k--;
        }
        
        return res.toString();
    }
}

 

posted @ 2015-07-10 22:18  ~每天进步一点点~  阅读(143)  评论(0编辑  收藏  举报