字符串相乘

题目描述:给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/multiply-strings/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:数组遍历
  • 首先,如果num1和num2有为0的,直接返回空字符串。
  • 否则,声明一个list为temp用来记录每一行的乘积的结果;
  • 然后将这些行的结果累加起来;
  • 最后将累加的结果按倒序拼成字符串返回。
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class LeetCode_043 {
  4. public static String multiply(String num1, String num2) {
  5. if ((num1 == null || num1.length() == 0) || (num2 == null || num2.length() == 0)) {
  6. return "";
  7. }
  8. if (num1.equals("0") || num2.equals("0")) {
  9. return "0";
  10. }
  11. /**
  12. * 如果num2的长度大于num1的长度将num1和num2的值交换
  13. */
  14. if (num2.length() > num1.length()) {
  15. String temp = num1;
  16. num1 = num2;
  17. num2 = temp;
  18. }
  19. /**
  20. * 记录每一行的乘积的结果
  21. */
  22. List<int[]> temp = new ArrayList<>();
  23. int count = 0;
  24. for (int i = num2.length() - 1; i >= 0; i--) {
  25. int c2Num = num2.charAt(i) - '0';
  26. int[] cur = new int[num1.length() + num2.length()];
  27. int index = 0;
  28. for (; index < count; index++) {
  29. cur[index] = 0;
  30. }
  31. int addOne = 0;
  32. for (int j = num1.length() - 1; j >= 0; j--) {
  33. int c1Num = num1.charAt(j) - '0';
  34. if (c2Num * c1Num + addOne > 9) {
  35. cur[index++] = (c2Num * c1Num + addOne) % 10;
  36. addOne = (c2Num * c1Num + addOne) / 10;
  37. } else {
  38. cur[index++] = c2Num * c1Num + addOne;
  39. addOne = 0;
  40. }
  41. }
  42. if (addOne > 0) {
  43. cur[index] = addOne;
  44. }
  45. temp.add(cur);
  46. count++;
  47. }
  48. int addOne = 0;
  49. List<Integer> result = new ArrayList<>();
  50. /**
  51. * 将每一行的乘积结果累加起来
  52. */
  53. for (int i = 0; i < num1.length() + num2.length(); i++) {
  54. int curNum = addOne;
  55. for (int[] ints : temp) {
  56. curNum += ints[i];
  57. }
  58. if (curNum > 9) {
  59. result.add(curNum % 10);
  60. addOne = curNum / 10;
  61. } else {
  62. result.add(curNum % 10);
  63. addOne = 0;
  64. }
  65. }
  66. String resultStr = "";
  67. int firstNoneZeroIndex = -1;
  68. /**
  69. * 找到第一个不为0的数字
  70. */
  71. for (int i = result.size() - 1; i >= 0; i--) {
  72. if (result.get(i) != 0) {
  73. firstNoneZeroIndex = i;
  74. break;
  75. }
  76. }
  77. /**
  78. * 将最后的结果拼成string并最后返回
  79. */
  80. for (int i = firstNoneZeroIndex; i >= 0; i--) {
  81. resultStr += String.valueOf(result.get(i));
  82. }
  83. return resultStr;
  84. }
  85. public static void main(String[] args) {
  86. // 测试用例,预计输出: 56088
  87. System.out.println(multiply("123", "456"));
  88. }
  89. }

【每日寄语】 再长的路,一步步也能走完,再短的路,不迈开双脚也无法到达。