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.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
思路:模拟乘法。数组记录。
1 public class Solution { 2 public String multiply(String num1, String num2) { 3 if (num1 == null || num2 == null) { 4 return null; 5 } 6 7 int len = num1.length() + num2.length(); 8 int i, j, product, carry; 9 int[] num3 = new int[len]; 10 for (i = num1.length() - 1; i >= 0; i--) { 11 carry = 0; 12 for (j = num2.length() - 1; j >= 0; j--) { 13 product = carry + num3[i + j + 1] + Character.getNumericValue(num1.charAt(i)) * Character.getNumericValue(num2.charAt(j)); 14 num3[i + j + 1] = product % 10; 15 carry = product / 10; 16 } 17 num3[i + j + 1] = carry; 18 } 19 i = 0; 20 while (i < len && num3[i] == 0) { 21 i++; 22 } 23 StringBuilder sb = new StringBuilder(); 24 if (i == len) { 25 sb.append(0); 26 } 27 while (i < len) { 28 sb.append(num3[i++]); 29 } 30 return sb.toString(); 31 32 } 33 }

浙公网安备 33010602011771号