[Leetcode]multiply-strings Java code

Source: Internet
Author: User

Topic:

Given numbers represented as strings, return multiplication of the numbers as a string.

Note:the numbers can be arbitrarily large and is non-negative.

Give two numbers represented by a string to multiply them.

Note: Numbers are non-negative and can be infinitely large

————————————————————————

Before considering the number can be infinitely large, the method is to convert the string into a number, and then multiply, the product again into a string output,

The last discovery is that only a subset of the test cases can pass, for numbers that exceed the long type representation range.

-----------------------------------------------------

Method of thinking: Based on the multiplication of the calculus process

------------------------------------------

Code: (Can be AC on the cow, but Leetcode has a use case, timeout problem)

 Public classSolution { Publicstring Multiply (string num1, String num2) {if(Num1.equals ("0") | | num2.equals ("0"))            return"0"; if(Num1.charat (0) = = '-' | | Num2.charat (0) = = '-')            return"False"; intlen_num1,len_num2; Len_num1=num1.length (); Len_num2=num2.length (); String [] Sing_mul=Newstring[len_num2]; intmaxlen_sing = 0;  for(intz=0; z<len_num2; z++)//InitializeSing_mul[z] = ""; intTimes = 0; //The multiplier * Multiplier--Returns the string array Sing_mul, and each element is a result of a multiplier that is multiplied by a number of digits.          for(inti=len_num2-1; i>=0; i--){            intNum2cur = Integer.parseint (string.valueof (Num2.charat (i)));//one of the multipliers            intAdd = 0; String Temp= ""; //a multiplicative bit * is multiplied by a multiplier---> returns is a string             for(intJ=len_num1-1; j>=0; j--) {//iterate through each bit of the multiplier                intNum1cur =Integer.parseint (String.valueof (Num1.charat (j))); intMulcur = num1cur * num2cur +add; Temp+ = string.valueof (mulcur%10); Add= MULCUR/10; }            if(Add! = 0) {Temp+=string.valueof (add); } stringbuffer sb_temp=NewStringBuffer (temp); StringBuffer Temp_rev=Sb_temp.reverse ();            String str_temp; Str_temp=temp_rev.tostring (); //added "0" at the end;             for(intz=0; z<times; z++) Str_temp+ = "0"; Sing_mul[i]=str_temp; Times++; //maxlen_sing The maximum length of an element in a string array Sing_mul            if(Sing_mul[i].length () >maxlen_sing) maxlen_sing=sing_mul[i].length (); }         //Adds all the elements in an array of strings. String result = Sing_mul[0];  for(intZ=1; z<len_num2; z++){            intLen_res =result.length (); //Add "0" to the short string before.            if(Sing_mul[z].length () <len_res) {//fill the front of the string//reverse the string, fill "0", and invert the string again. StringBuffer sb_z =NewStringBuffer (Sing_mul[z]); String Sb_z_str=sb_z.reverse (). toString ();  for(intw=0; w< (Len_res-sing_mul[z].length ()); w++) Sb_z_str+ = "0"; StringBuffer sb_temp=NewStringBuffer (SB_Z_STR); SING_MUL[Z]=sb_temp.reverse (). toString (); }            intadd_ = 0; String Temp_str= "";  for(inti=len_res-1; i>=0; i--){                intN1 =Integer.parseint (string.valueof (Result.charat (i))); intN2 =Integer.parseint (string.valueof (Sing_mul[z].charat (i))); intTEP = n1+n2+add_; Add_= TEP/10; Temp_str+ = Tep%10; }            if(Add_! = 0) {Temp_str+=string.valueof (add_); } stringbuffer sb_temp_str=NewStringBuffer (TEMP_STR); Result=sb_temp_str.reverse (). toString (); }        returnresult; }     Public Static voidmain (String [] args) {solution Mulstr=Newsolution (); String result= Mulstr.multiply ("9133", "0");     System.out.print (result); }}

Code Explanation:

1. NUM1 is the multiplier, num2 as a multiplier, with each multiplier to multiply by the multiplier, get a string---"will eventually get the string array Sig_mul, which contains the multiplication of the number of digits of a string

(Note: In addition to the last multiply digit, the rest of the multiply digits and the strings that are equal to the multiplier should be added at the end of the corresponding number of "0")

2. The string in sig_mul[0] is the longest, so result = Sig_mul[0]

3. Add the elements in result and Sig_mul each time (1<=i<sig_mul.length)

( Note: The number of digits after each addition varies, but the number of bits in result is the same as it always represents the longest number of digits )

(Note: Each time an element in Sig_mul and result is added, the number of bits <result the sig_mul[i] should be given to Sig_mul[i] before the corresponding number of digits is "0", So that the number of bits of the two added strings is equal and can be added )

4. String reverse are frequently used in this process.

(Because each addition or multiplication starts at the end of the string, and the correct string should be a reversed string that multiplies or adds the result)

The transformation is in the form of string conversion stringbuffer--"using Stringbuffer.reverse ()--" StringBuffer conversion string

-----------------------------------------

Some issues have not been resolved and are later updated.

[Leetcode]multiply-strings Java code

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.