怎么用Java把输入的两串字符串中的数字提取出来,并且将两串数字相乘输出?

如题所述

第1个回答  2021-05-28

解决方案:

    使用正则表达式抽取数字子串;

    使用Interger.parse将数字子串转为整数类型

    计算两个数字相乘即可;

第2个回答  2021-05-27
// 字符串乘积
// 时间复杂度: O(m * n)
// 空间复杂度: O(m + n)
public String multiply(String num1, String num2) {

if(num1 == null || num2 == null
|| num1.length() == 0 || num2.length() == 0
|| num1.equals("0") || num2.equals("0")){
return "0";
}
int m = num1.length() - 1, n = num2.length() - 1;
int[] temp = new int[m + n + 2]; // 空间复杂度O(m + n)
for(int i = m; i >= 0; i-- ){ // 时间复杂度: O(m*n)
int x = num1.charAt(i) - '0';
for(int j = n; j >= 0; j--){
int y = num2.charAt(j) - '0';
temp[i + j + 1] += x*y;
}
}
for(int i = temp.length - 1; i > 0; i--){ //时间复杂度: O(n+m)
temp[i-1] += temp[i] / 10;
temp[i] = temp[i] % 10;
}
int index = temp[0] == 0 ? 1 : 0;
StringBuilder sb = new StringBuilder();// 空间复杂度 O(m + n)
for(int i = index; i < temp.length; i++){ // 时间复杂度 O(n + m)
sb.append(temp[i]);
}
return sb.toString();
}
第3个回答  2021-05-27
正则表达式+BigDecimal
相似回答