leetcode -- Multiply Strings
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.
大整数乘法,一位一位往上乘,注意进位的处理即可。此外,注意0的处理
1 public class Solution { 2 public String multiply(String num1, String num2) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int l1 = num1.length(); 6 int l2 = num2.length(); 7 8 int[] num = new int[l1 + l2 + 1]; 9 for(int i = 0; i <= l2 - 1; i ++){ 10 int carry = 0; 11 int a = num2.charAt(l2 - 1 - i) - '0'; 12 for(int j = 0; j <= l1 - 1; j ++){ 13 int b = num1.charAt(l1 - 1 - j) - '0'; 14 num[i + j] += a * b + carry; 15 carry = num[i + j] / 10; 16 num[i + j] = num[i + j] % 10; 17 } 18 num[i + l1] = carry; 19 } 20 21 int i = num.length - 1; 22 while(i > 0 && num[i] == 0){ 23 i--; 24 } 25 26 StringBuilder sb = new StringBuilder(); 27 while(i >= 0){ 28 sb.append(num[i--]); 29 } 30 return sb.toString(); 31 } 32 }
ref:http://gongxuns.blogspot.com/2013/01/leetcode-multiply-strings.html