【题目描述】

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

注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数

​https://leetcode.cn/problems/multiply-strings/​

【示例】

【LeeCode】43. 字符串相乘_java


【代码】admin

思路:利用已知的方法

package com.company;
// 2023-03-06
import java.math.BigInteger;
import java.util.*;

class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
BigInteger x = new BigInteger(num1);
BigInteger y = new BigInteger(num2);
BigInteger multiply = x.multiply(y);

return multiply.toString();
}
}

public class Test {
public static void main(String[] args) {
System.out.println(Math.floorMod(-1, 5));
new Solution().multiply("2", "3"); // 输出: 6
new Solution().multiply("123", "456"); // 输出: 56088
}
}


value.Of(x)

 这个函数的作用是将括号内的参数转换成指定的数据类型


​int A=42;

•   BigInteger f=BigInteger.valueOf(A);

//输出的f将会等于BigInteger型的42

•   System.out.println("f="+f);

add()

​大整数​加起来

subtract()

将大整数相减

multiply()

​将大整数相乘



【LeeCode】43. 字符串相乘_java_02



divide()

将大整数做除法



【LeeCode】43. 字符串相乘_大整数_03



compareTo()

比较两个大整数大小的

gcd()

将两个大整数取最大公约数

abs()

这个函数的作用是取绝对值,

negate()

这个函数的作用是取数的相反数

mod()

对数进行取余 

自定义进制

类型

String str = "1011100111";

// radix代表二进制,为下一行代码中的参数radix赋值

int radix = 2;  

// 输出:743

BigInteger interNum1 = new BigInteger(str,radix);

控制台读入



【LeeCode】43. 字符串相乘_大整数_04



【代码】LeeCode

​​​​https://leetcode.cn/problems/multiply-strings/solutions/372098/zi-fu-chuan-xiang-cheng-by-leetcode-solution/​

【LeeCode】43. 字符串相乘_java_05

package com.company;
// 2023-03-06
import java.math.BigInteger;
import java.util.*;

class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}

String res = "0";

int m = Integer.parseInt(num1);
int n = num2.length();
String sum = "0";
int count = 0;
for (int i = n - 1; i >= 0; i--){
int index = n - i;
long tmp =(long) m * (num2.charAt(i) - '0');
StringBuilder sb = new StringBuilder();
int xx = index;
sb.append(String.valueOf(tmp));
while (xx > 1){
sb.append("0");
xx--;
}
System.out.println(sb.toString());
res = addString(sum, sb.toString());
count += Integer.parseInt(res);
System.out.println("count: "+ count);
sum = String.valueOf(count);
}
System.out.println(sum);
return res;
}

// 字符串相加
private String addString(String num1, String num2) {
int m = num1.length() - 1;
int n = num2.length() - 1;
int res = 0;
StringBuilder sb = new StringBuilder();
while (m >= 0 || n >= 0 || res != 0){
int x = m >= 0 ? num1.charAt(m) - '0' : 0;
int y = n >= 0 ? num2.charAt(n) - '0' : 0;

int sum = x + y + res;
// 个位
sb.append(sum % 10);
// 十位
res = sum / 10;
m--;
n--;
}
return sb.reverse().toString();
}
}

public class Test {
public static void main(String[] args) {
// new Solution().multiply("2", "3"); // 输出: 6
new Solution().multiply("1234", "567"); // 输出: 56088
}
}

【代码】分块

​https://blog.csdn.net/weixin_44131922/article/details/128375966​