Put the code on first.
1 Publicstring Multiply (string num1, String num2) {2String str = "";3StringBuffer SB =NewStringBuffer (NUM1);4NUM1 =sb.reverse (). toString ();5SB =NewStringBuffer (num2);6num2 =sb.reverse (). toString ();7 int[] res =New int[Num1.length () +num2.length ()];8 for(inti = 0; I < num1.length (); i++) {9 for(intj = 0; J < Num2.length (); J + +) {TenRes[i + j] + = (Num1.charat (i)-' 0 ') * (Num2.charat (j)-' 0 '); One } A } - intK = 0, contribute = 0; - while(K < Res.length | | Contribute > 0) { the intTMP = k<res.length?res[k]:0; -TMP = contribute+tmp; -contribute = TMP/10; -str + = Tmp%10; +k++; - } +SB =NewStringBuffer (str); Astr =sb.reverse (). toString (); at inti = 0; - while(I<str.length () &&str.charat (i) = = ' 0 ') -i++; - if(i<str.length ()) { -str =str.substring (i); -}Else{ instr = "0"; - } to returnstr; +}
View Code
Ideas are as follows:
Simulate vertical multiplication
1, conversion and reversal, word order reversal;
2, by phase multiplication, the results are stored in res[i+j];
3, processing carry;
4. Convert and invert, convert the result of the calculation to a string and invert.
5, eliminate the excess of 0;
Multiplied by two numbers, the length of the result must not be greater than the sum of the multiplier and the length of the multiplier.
The above can also be implemented by using the BigInteger class of Java directly
Public Static void Main (string[] args) { = "98989898989898956898", B = "989892551548781251323265615150"; New BigInteger (a); New BigInteger (b); System.out.println (aa.multiply (BB)); }
View Code
Multiply Strings large number multiplied by Java