categories: [Blog,Algorithm]


43. 字符串相乘

难度中等574
给定两个以字符串形式表示的非负整数 num1num2,返回 num1num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = “2”, num2 = “3”
输出: “6”
示例 2:
输入: num1 = “123”, num2 = “456”
输出: “56088”
说明:

  1. num1num2 的长度小于110。
  2. num1num2 只包含数字 0-9
  3. num1num2 均不以零开头,除非是数字 0 本身。
  4. 不能使用任何标准库的大数类型(比如 BigInteger)直接将输入转换为整数来处理
  1. class Solution {
  2. public String multiply(String num1, String num2) {
  3. if (num1.equals("0") || num2.equals("0")) {
  4. return "0";
  5. }
  6. int m = num1.length(), n = num2.length();
  7. int[] ansArr = new int[m + n];//最多位数
  8. for (int i = m - 1; i >= 0; i--) {
  9. int x = num1.charAt(i) - '0';//字母转数字 倒序
  10. for (int j = n - 1; j >= 0; j--) {
  11. int y = num2.charAt(j) - '0';
  12. ansArr[i + j + 1] += x * y;
  13. }
  14. }
  15. for (int i = m + n - 1; i > 0; i--) {
  16. ansArr[i - 1] += ansArr[i] / 10;
  17. ansArr[i] %= 10;//进位处理
  18. }
  19. int index = ansArr[0] == 0 ? 1 : 0;//去掉前缀0
  20. StringBuffer ans = new StringBuffer();
  21. while (index < m + n) {
  22. ans.append(ansArr[index]);
  23. index++;
  24. }
  25. return ans.toString();
  26. }
  27. }