个人记录-LeetCode 43. Multiply Strings

    xiaoxiao2021-12-14  24

    问题: Given two numbers represented as strings, return multiplication of the numbers as a string.

    Note: 1、The numbers can be arbitrarily large and are non-negative. 2、Converting the input string to integer is NOT allowed. 3、You should NOT use internal library such as BigInteger.

    代码示例:

    如上图所示,将平常计算乘法的步骤一步一步表示出来。 可以发现nums1[i]与nums2[j]位相乘的结果,将写在结果的第i+j、i+j+1位。

    public class Solution { public String multiply(String num1, String num2) { if (num1.equals("0") || num2.equals("0")) { return "0"; } int len1 = num1.length(); int len2 = num2.length(); int[] rst = new int[len1 + len2]; for (int i = 0; i < len1; ++i) { for (int j = 0; j < len2; ++j) { int temp = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); rst[i+j] += temp / 10; rst[i+j+1] += temp % 10; //以下是处理进位 if (rst[i+j+1] >= 10) { rst[i+j+1] -= 10; rst[i+j] += 1; } for (int k = i + j; k > 0; --k) { if (rst[k] >= 10) { rst[k] -= 10; rst[k-1] += 1; } else { break; } } } } StringBuilder sb = new StringBuilder(""); int i = 0; //处理首位为0的情况 if (rst[0] == 0) { i = 1; } for (; i < rst.length; ++i) { sb.append(rst[i]); } return sb.toString(); } }
    转载请注明原文地址: https://ju.6miu.com/read-970322.html

    最新回复(0)