描写叙述:
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
思路:
简而言之,要实现的就是BigInteger(a).Multiply(BigInteger(b))的功能,但非常显然,leetcode中不让用BigInteger
代码:
public class Solution { public String multiply(String num1, String num2) { if(num1==null||num2==null) return new String(); num1=num1.trim(); num2=num2.trim(); if(num1.equals("0")||num2.equals("0")) return "0"; List<Integer>listNum1=new ArrayList<>(); List<Integer>listNum2=new ArrayList<>(); List<Integer>listResult=new ArrayList<>(); int len1=num1.length(); int len2=num2.length(); int i=0,j=0,lenResult=0,index=0; int baseNum=0,flowNum=0,tempNum1=0,tempNum2=0; for( i=len1-1;i>=0;i--) listNum1.add(num1.charAt(i)-'0'); for( i=len2-1;i>=0;i--) listNum2.add(num2.charAt(i)-'0'); tempNum2=listNum2.get(0); for(i=0;i<len1;i++) { tempNum1=listNum1.get(i); tempNum1=tempNum1*tempNum2+flowNum; baseNum=tempNum1%10; flowNum=tempNum1/10; listResult.add(baseNum); } if(flowNum!=0) { listResult.add(flowNum); flowNum=0; } for(j=1;j<len2;j++) { baseNum=0;flowNum=0; tempNum2=listNum2.get(j); lenResult=listResult.size(); for(i=0;i<len1;i++) { index=i+j; if(index<lenResult) { tempNum1=listNum1.get(i); tempNum1=tempNum1*tempNum2+flowNum+listResult.get(index); baseNum=tempNum1%10; flowNum=tempNum1/10; listResult.set(index, baseNum); } else { tempNum1=listNum1.get(i); tempNum1=tempNum1*tempNum2+flowNum; baseNum=tempNum1%10; flowNum=tempNum1/10; listResult.add(baseNum); } } if(flowNum!=0) { listResult.add(flowNum); flowNum=0; } } if(flowNum!=0) listResult.add(flowNum); StringBuilder sBuilder=new StringBuilder(); for(int num:listResult) sBuilder.append(num); sBuilder.reverse(); return sBuilder.toString(); } }