Straight forward idea. Just like the way we multiply numbers. Don't forget considering the carry and be careful. e.g.
123*456,what we usually do is: 123* 456----------- 738 615+492----------- 56088thus, 123*456 = 56088.In the same way, the algorithm is:from end to start position, use a new array to store temproary digit.
A*B(1)For each element B[i] Compute tmp = B[i]*A Add tmp to the previous result, note the start position. res = res"+"tmp(2)Return result.To be specific,(1) char2int, int(char-'0');(2) int2char, char(int+'0')(3) Don't forget the carry in each add or multiply operation.(4) Don't forget the carry after last operation. e.g. 82+33 = 115.(5) Be careful with the string order and the number order.public class Solution { public String multiply(String num1, String num2) { //用字符串模拟乘法,注意事项见上面分析。注意result的第0位是结果的个位 int len1=num1.length(); int len2=num2.length(); int[] result=new int[len1+len2]; int carry=0; int i=0; int j=0; for( i=0;i0){ if(result[i]!=0) break; i--; } StringBuilder res=new StringBuilder(); int k=i; while(k>=0){ res.append((char)(result[k]+'0'));//res.append(result[k]+'0');会得整数,比如result[k]为0时,添加的是48 k--; } return res.toString(); }}