[leetcode]43. Multiply Strings@Java

本文介绍了一种解决大数相乘问题的高效算法,并通过一个具体的LeetCode题目进行实践。该算法避免了使用内置的大整数库或直接将输入转换为整数,适用于处理非常大的数字相乘的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这其实是一道大数相乘问题,类似的题目我之前的博客已经发过了,今天相当于复习一下吧


https://leetcode.com/problems/multiply-strings/#/description


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.


package go.jacob.day721;
/**
 * 43. Multiply Strings
 * @author Jacob
 *
 */
public class Demo1 {
	/*
	 * 大数相乘
	 * Runtime: 21 ms.Your runtime beats 99.95 % of java submissions.
	 * 用空间换时间:如果有空间要求的话,可以不建立arr1和arr2数组,直接在计算的时间用num1.charAt(i)-'0'即可
	 */
	public String multiply(String num1, String num2) {
		if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0)
			return null;
		if(num1.equals("0")||num2.equals("0"))
			return "0";
		int len1 = num1.length(), len2 = num2.length();
		int[] arr1 = new int[len1], arr2 = new int[len2];
		// 首尾交换,便于计算
		for (int i = 0; i < len1; i++) {
			arr1[len1 - 1 - i] = num1.charAt(i) - '0';
		}
		for (int i = 0; i < len2; i++) {
			arr2[len2 - 1 - i] = num2.charAt(i) - '0';
		}
		// 两数相乘结果的长度介于len1*len2-1到len1*len2
		int[] res = new int[len1 + len2];
		for (int i = 0; i < len1; i++) {
			for (int j = 0; j < len2; j++) {
				res[i + j] += arr1[i] * arr2[j];
			}
		}
		for (int i = 0; i < len1 + len2; i++) {
			while (res[i] >9) {
				res[i + 1] += res[i] / 10;
				res[i] = res[i] % 10;
			}
		}
		StringBuilder ans=new StringBuilder();
		for (int i = len1 + len2-1; i >=0; i--) {
			ans.append(res[i]);
		}
		//如果第一个元素是0,去除
		return ans.charAt(0) == '0' && ans.length() != 1 ? ans.substring(1) : ans.toString();
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值