[leedcode 43] Multiply Strings

來源:互聯網
上載者:User

標籤:

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

 

[leedcode 43] Multiply Strings

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.