Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

解决方案如下:

Remember how we do multiplication?

Start from right to left, perform multiplication on every pair of digits, and add them together. Let's draw the process! From the following draft, we can immediately conclude:

 `num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]` 

代码如下:

public class MultiplyStrings {

	public static void main(String[] args) {
		System.out.println(multiply("123","456"));
	}
	
	public static String multiply(String num1,String num2){
		int m = num1.length(),n = num2.length();
		int[] pos = new int[m+n];
		
		for(int i=m-1;i>=0;i--){
			for(int j=n-1;j>=0;j--){
				int mul = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
				int p1 = i+j , p2 = i+j+1;
				int sum = mul +pos[p2];		//注意加上上一步的结果
				System.out.println(pos[p1]+"__"+pos[p2]);
				pos[p1] += sum/10;		
				pos[p2] = sum%10;
			}
		}
		
		StringBuilder sb = new StringBuilder();
		for(int p : pos){
			if(!(sb.length() == 0 && p==0))
				sb.append(p);
		}
		
		return sb.length() == 0 ? "0" : sb.toString();
		
	}
}



您可以使用字符串来实现高精度的加法和乘法运。下面是一个示例的实现代码: ``` def addStrings(num1, num2): # 将字符串转换为整数列表 n1 [int(x) for in num1] n = [int(x) for x in num2] # 对齐两个整数列表的长度 if len(n1) < len(n2): n1 = [0] * (len(n2) - len(n1)) + n1 else: n2 = [0] * (len(n1) - len(n2)) + n2 # 逐位相加 carry = 0 res = [] for i in range(len(n1)-1, -1, -1): total = n1[i] + n2[i] + carry carry = total // 10 res.append(str(total % 10)) # 如果还有进位,需要额外加一位 if carry: res.append(str(carry)) # 翻转并返回结果 return ''.join(res[::-1]) def multiplyStrings(num1, num2): # 将字符串转换为整数列表 n1 = [int(x) for x in num1][::-1] n2 = [int(x) for x in num2][::-1] # 初始化结果列表 res = [0] * (len(n1) + len(n2)) # 逐位相乘 for i in range(len(n1)): for j in range(len(n2)): res[i+j] += n1[i] * n2[j] res[i+j+1] += res[i+j] // 10 res[i+j] %= 10 # 去除前导零 while len(res) > 1 and res[-1] == 0: res.pop() # 翻转并返回结果 return ''.join(str(x) for x in res[::-1]) ``` 您可以使用`addStrings`函数进行两个字符串的加法运算,使用`multiplyStrings`函数进行两个字符串的乘法运算。例如: ```python num1 = "123456789" num2 = "987654321" print(addStrings(num1, num2)) # 输出:1111111110 print(multiplyStrings(num1, num2)) # 输出:121932631112635269 ``` 这样就可以实现高精度的加法和乘法运算了。希望对您有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值