题目描述:
解题思路:
java代码:
1 public class LeetCode43 { 2 public static void main(String[] args) { 3 String num1="123"; 4 String num2="45"; 5 System.out.println(num1+"和"+num2+"相乘的结果是:"+new Solution().multiply(num1, num2)); 6 } 7 } 8 9 class Solution { 10 public String multiply(String num1, String num2) { 11 int len1=num1.length(),len2=num2.length(); 12 int[] result=new int[len1+len2]; 13 for(int i=len1-1;i>=0;i--){ 14 for(int j=len2-1;j>=0;j--){ 15 int mul=(num1.charAt(i)-'0')*(num2.charAt(j)-'0'); 16 int p1=i+j,p2=i+j+1; 17 int sum=mul+result[p2]; 18 19 result[p1]+=sum/10; 20 result[p2]=sum%10; 21 } 22 } 23 StringBuilder sb=new StringBuilder(); 24 for(int e:result){ 25 if(!(sb.length()==0&&e==0))//若最高位是0,去除 26 sb.append(e); 27 } 28 return sb.length()==0?"0":sb.toString(); 29 } 30 }
测试结果: