Write multi-digit multiplication with Java

Source: Internet
Author: User
Tags first string

A friend encountered a problem during the interview, write programs in Java, calculate two 20-digit multiplication. Listen, it's funny, just try to make it.

The idea is to use code to simulate the process of multiplying the hand, that is, the multiplication of a bit, the result remains on the corresponding bit, and the rounding problem is solved.

Ask if the other side is solved, the other side told me that Java has a Java.math.BigInteger package, there is a BigInteger s1=new BigInteger (a); Receive string type data, you can use S1.multiply ( S2) is multiplied by a large number of digits.

Here's My Code:

ImportJava.math.BigInteger;ImportJava.util.Map;ImportJava.util.Scanner;ImportJava.util.TreeMap; Public  class chengfa {    StaticMap<integer, integer> map1 =NewTreemap<integer, integer> ();//Store the first number entered by the user, the key is the number of digits, 123 in turn represents a 1000, and so on, the value is the number of that bit.     StaticMap<integer, integer> map2 =NewTreemap<integer, integer> ();//Store The second number entered by the user, meaning the same as map1.     StaticMap<integer, integer> map3 =NewTreemap<integer, integer> ();//Store The calculated results, the keys and values have the same meaning as MPA1.     Static intCalcnumber=0;//used to count the number of times     Public Static void Main(string[] args) {System.out.println ("Please enter the first number:"); Scanner in =NewScanner (system.in); String a = In.next ();//Receive the first number entered by the user, saved as a string typeSystem.out.println ("Please enter a second number:"); String B = In.next ();//Receive a second number entered by the user, saved as String typeMap1=savetomap (a);//The number in string A is stored in the Map1 collection by BitsMap2=savetomap (b);//The number in string b is stored in the Map1 collection by BitsMap3=calc (Map1, MAP2);        String Result=getresult (MAP3); System.out.println (The answer to the product is: "+ result); System.out.println ("The total number of operations is:"+calcnumber); BigInteger s1=NewBigInteger (a); BigInteger s2=NewBigInteger (b); System.out.println ("The answer with Java.math.BigInteger:"+s1.multiply (S2)); }/** * The string entered by the user is stored in the map collection by bits * @param number passed in the parameter for the user input string * @return Returns the map collection of the saved numbers */
          Public StaticMap<integer, integer>Savetomap(String number) {Map<integer, integer> maptemp =NewTreemap<integer, integer> ();intLength = Number.length ();//The length of the passed string is taken out so that in the following loop, the number flashback is placed in the map collection         for(intm =1; M <= number.length (); m++) {//Converts the first string entered into a single number and places it in Map1Maptemp.put (length--, integer.parseint (number.substring (M-1, m)));//Put the digits in the string flashback into the map collection}returnMaptemp; }/** * Nesting of 2 for loops, realizing that each number in the MAP1 is multiplied by each number in the MAP2, and the result is saved in the result set in a bitwise * @param map1 * @param map2 * @return * *     Public StaticMap<integer, integer>Calc(Map<integer, Integer> map1, Map<integer, integer> map2) {Map<integer, integer> mapTemp1 =NewTreemap<integer, integer> (); for(intTotal =1; Total <= map1.size () + map2.size (); total++) {//Initialize data in MAPTEMP1 to avoid null pointer problems when saving numbersMaptemp1.put (Total,0); } for(inti =1; I <= map1.size (); i++) {//First layer cycle, when 1 take map1 in the bit, when 2 take map1 10 bits, according to this sliding scale             for(intK =1; K <= Map2.size (); k++) {///second layer loop, when 1 take map2 in the bit, when 2 take MAP2 10 bits, according to this sliding scale                intRESULT1 = Map1.get (i) * Map2.get (k);//The number of I in the map1 is multiplied with each position in the MAP2, RESULT1 is the productcalcnumber++;intCurrentnum = k + I-1;if(RESULT1/Ten==0) {//When the result of the product is single digit, enter this code block, only need to put the bits inAddnumber (Currentnum, RESULT1,MAPTEMP1); }Else{//When the product is a two-digit number, enter this code block, first put the bits in, and then put the ten inAddnumber (currentnum, result1%Ten, MAPTEMP1);//Place the position of the Currentnum in the Map3 collectionAddnumber (Currentnum +1, RESULT1/Ten, MAPTEMP1);//Put ten to the next position of Currentnum in the Map3 collection}            }        }returnMAPTEMP1; }/** * The operation method that saves the result of the operation to this bit, mainly to solve the rounding problem that is greater than 9 after the addition of the number * @param where the currentnum result should be placed (number of digits) * @param Res Ult the value that needs to be put in this position * /     Public Static void Addnumber(intCurrentnum,intResult,map<integer, integer> Resultmap) {intResulttem = Resultmap.get (currentnum) + result;if(Resulttem/Ten==0) {//If the Resulttem is single digit, add it directly to the location, no need to consider rounding issuesResultmap.put (Currentnum, Resulttem);        calcnumber++; }Else{//If the Resulttem is a two-digit number, you need to consider rounding issuesResultmap.put (currentnum, Resulttem%Ten);//Add single digit to this locationAddnumber (Currentnum +1, Resulttem/Ten, Resultmap);        calcnumber++; }    }/** * method to convert the results inside map3 to a string type for final display to the user * @param resultmap * @return * /     Public StaticStringGetResult(Map<integer, integer> resultmap) {String result=""; for(intg = Resultmap.size (); G >=1; g--) {if(Resultmap.get (g) = =0&& Result.equals ("")) {//If Map3.get (g) is 0 and there is no number in result, it proves to be 0 omitted before, do not do any action}Else{result + = Resultmap.get (g) +""; }        }returnResult }}

Write multi-digit multiplication with Java

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.