字符串相乘

mac2022-06-30  31

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

示例 1:

输入: num1 = “2”, num2 = “3” 输出: “6” 示例 2:

输入: num1 = “123”, num2 = “456” 输出: “56088” 说明:

num1 和 num2 的长度小于110。 num1 和 num2 只包含数字 0-9。 num1 和 num2 均不以零开头,除非是数字 0 本身。 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。 在真实的面试中遇到过这道题?

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

public class MultiplyString { public static String multiply(String num1, String num2) { //两个数字相乘,得到的结果的最大位数为两个相乘元素的长度的和 int[] result = new int[num1.length() + num2.length()]; for (int i = num1.length() - 1; i >= 0; i--) { for (int j = num2.length() - 1; j >= 0; j--) { result[i + j + 1] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); } } int carry = 0; for (int i = num1.length() + num2.length() - 1; i >= 0; i--) { result[i] += carry; if (result[i] > 9) { carry = result[i] / 10; result[i] = result[i] % 10; } else { carry = 0; } } boolean isPreFixZero = true; StringBuilder resultStr = new StringBuilder(); for (int i = 0; i < num1.length() + num2.length(); i++) { if (isPreFixZero && result[i] != 0) { // 判断是否是前缀的零,如果是前缀的零,如果不是前缀的零,就开始作为结果添加。 isPreFixZero = false; } if (!isPreFixZero) { resultStr.append(result[i]); } } if (resultStr.length() == 0) { // 当所有的数字都为0的时候,至少有一个零 resultStr.append('0'); } return resultStr.toString(); } public static void main(String[] args) { System.out.println(multiply("12342143","123")); System.out.println(multiply("0","0")); } }
最新回复(0)