Java [Leetcode 43]Multiply Strings

题目描述:

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.

解题思路:

设置数组记录单个位置相乘的结果,最后负责相加进位。

代码如下:

public class Solution {
    public String multiply(String num1, String num2) {
		int num1Length = num1.length();
		int num2Length = num2.length();
		int d1, d2;
		int carry = 0;
		int temp;
		int[] caculate = new int[num1Length + num2Length];
		StringBuilder sb = new StringBuilder();

		for (int i = num1.length() - 1; i >= 0; i--) {
			d1 = num1.charAt(i) - '0';
			for (int j = num2.length() - 1; j >= 0; j--) {
				d2 = num2.charAt(j) - '0';
				caculate[i + j + 1] += d1 * d2;
			}
		}

		for (int i = caculate.length - 1; i >= 0; i--) {
			temp = (caculate[i] + carry) % 10;
			carry = (caculate[i] + carry) / 10;
			caculate[i] = temp;
		}

		for (int num : caculate)
			sb.append(num);

		while (sb.length() > 1 && sb.charAt(0) == '0') {
				sb.deleteCharAt(0);
		}

		return sb.toString();

	}
}

  

原文地址:https://www.cnblogs.com/zihaowang/p/5027514.html