字符串相乘——求字符串的乘积
原创
©著作权归作者所有:来自51CTO博客作者yangshanyang的原创作品,请联系作者获取转载授权,否则将追究法律责任
给定两个字符串:num1=“123”,num2=“456”,不能使用大数BigInterger和直接转换成数字来处理,计算结果,存为字符串
package com.Leetcode.字符串相乘;
/**
* @author
* @date 2020/9/30
* 给定两个字符串:num1=“123”,num2=“456”,不能使用大数BigInterger和直接转换成数字来处理,计算结果,存为字符串
* 思路:(1)先计算每一位数字相乘的结果,保存在集合中,不进行进位操作
* (2)遍历集合,进行进位操作
*/
public class StrMut {
public static void main(String[] args) {
String result = strMut("11","11");
System.out.println(result);
}
private static String strMut(String num1, String num2) {
if ("0".equals(num1) || "0".equals(num2)){
return "0";
}
int len1 = num1.length();
int len2 = num2.length();
//两个数字相乘,结果不会超过len1+len2的长度
int[] str = new int[len1 + len2];
//循环相乘,结果记录在数组中,不进位
for (int i = len1 - 1; i >= 0; i--) {
int n1 = num1.charAt(i) - '0';
for (int j = len2 - 1; j >= 0; j--) {
int n2 = num2.charAt(j) - '0';
str[i + j + 1] += n1 * n2;
}
}
//打印集合中数据,并做进位处理
for (int i = str.length - 1; i >= 1; i--) {
int num = str[i];
str[i] = num % 10;
int bitNum = num / 10;
str[i - 1] += bitNum;
}
//针对第一位数字为0开头的结果做过滤处理
int index = str[0]==0?1:0;
StringBuffer sb = new StringBuffer();
while (index<str.length){
sb.append(str[index]);
index++;
}
return sb.toString();
}
}