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.
solution:直接乘会溢出,需要一位一位的乘。
用一个数组d[]装所有一位乘积。
正确算法:
public class Solution { public String multiply(String num1, String num2) { String s1=new StringBuilder(num1).reverse().toString(); String s2=new StringBuilder(num2).reverse().toString(); int[] d= new int[s1.length()+s2.length()]; for(int i=0;i<s1.length();i++){ for(int j=0;j<s2.length();j++){ d[i+j]=d[i+j]+(s1.charAt(i)-'0')*(s2.charAt(j)-'0'); } } StringBuilder sb=new StringBuilder(); int carry; int digit; for(int temp=0;temp<d.length;temp++){ digit=d[temp]%10; carry=d[temp]/10; sb.insert(0,digit); if(temp<d.length-1) d[temp+1]=d[temp+1]+carry; } while(sb.length()>0 && sb.charAt(0)=='0'){ sb.deleteCharAt(0); } if(sb.length()==0){ return "0"; } return sb.toString(); } }