拼多多笔试题,做的时候有个细节没注意,一直不能AC。现在记录一下
思路:类似于自己手动计算两个数的乘法,位与位两两相乘,得到的数放入结果指定位,最后再考虑进位,把进位的数加到前一位上去。
//两个字符串大数相乘 public class BigMul { public String mul(String n1,String n2){ int len1=n1.length(); int len2=n2.length(); char[] num1=n1.toCharArray(); char[] num2=n2.toCharArray(); char temp; int temp1; for(int i=0;i<len1/2;i++){ temp=num1[i]; num1[i]=num1[len1-1-i]; num1[len1-1-i]=temp; } for(int i=0;i<len2/2;i++){ temp=num2[i]; num2[i]=num2[len2-1-i]; num2[len2-1-i]=temp; } int[] result=new int[len1+len2]; for(int i=0;i<len1;i++){ for (int j=0;j<len2;j++){ result[i+j]+=(Integer.valueOf(num1[i])-'0')*(Integer.valueOf(num2[j])-'0'); } } for(int i=0;i<len1+len2-1;i++){ if(result[i]>=10){ result[i+1]+=result[i]/10; result[i]%=10; } } for(int i=0;i<(len1+len2)/2;i++){ temp1=result[i]; result[i]=result[len1+len2-1-i]; result[len1+len2-1-i]=temp1; } StringBuilder resultString=new StringBuilder(); int k=0; while(result[k]==0){ k++; } for(int i=k;i<len1+len2;i++){ resultString.append(result[i]); } return resultString.toString(); } public static void main(String[] args) { /*Scanner in = new Scanner(System.in); String n1 = in.next(); String n2 = in.next();*/ String num1="2589741215"; String num2="568416617"; System.out.println(new BigMul().mul(num1,num2)); } }