[leetcode] Multiply Strings

本文提供了一种解决大数乘法问题的方法,通过字符串表示的大数进行乘法运算,并详细展示了实现的Java代码。该算法模拟了手算乘法的过程,适用于任意大的非负整数。

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

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

https://oj.leetcode.com/problems/multiply-strings/

思路:大数乘法,模拟笔算过程即可。

注意的细节:

  1. 前导0去掉;
  2. 结果为0;


代码:

import java.util.Arrays;

public class Solution {
	public String multiply(String num1, String num2) {
		if (num1 == null || num2 == null || num1.length() == 0
				|| num2.length() == 0)
			return null;
		int n1 = num1.length();
		int n2 = num2.length();

		char[] str1 = num1.toCharArray();
		char[] str2 = num2.toCharArray();
		char[] prod = new char[n1 + n2];

		Arrays.fill(prod, '0');

		int i, j;
		for (i = 0; i < n1; i++)
			for (j = 0; j < n2; j++) {
				prod[i + j] = (char) ((prod[i + j] - '0')
						+ (str1[n1 - 1 - i] - '0') * (str2[n2 - 1 - j] - '0') + '0');
			}


		int c = 0;
		for (i = 0; i < n1 + n2; i++) {
			prod[i] = (char) ((prod[i] - '0') + c + '0');
			if (prod[i] - '0' + c > 9) {
				c = (prod[i] - '0') / 10;
				prod[i] = (char) ((prod[i] - '0') % 10 + '0');
			} else
				c = 0;
		}


		StringBuilder sb = new StringBuilder();

		i = n1 + n2 - 1;
		while (i >= 0 && prod[i] == '0')
			i--;
		if (i == -1) {
			sb.append("0");
			return sb.toString();
		}

		for (; i >= 0; i--) {
			sb.append(prod[i]);
		}

		return sb.toString();
	}

	public static void main(String[] args) {
		System.out.println(new Solution().multiply("123", "12345"));
		System.out.println(new Solution().multiply("0", "123"));
		
	}
}




参考:

http://www.cnblogs.com/TenosDoIt/p/3735309.html

http://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/comment-page-1/#comment-122





转载于:https://my.oschina.net/jdflyfly/blog/284255

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值