Multiply Strings large number multiplied by Java

Source: Internet
Author: User
Tags multiply strings

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.