LeetCode-43. Multiply Strings (JAVA)大整数乘法

43. Multiply Strings

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

Note:

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

倾向于第二种解法:

参考:

两个非常大的数字相加,相减(JAVA)

第一种

LeetCode-43. Multiply Strings (JAVA)大整数乘法_第1张图片

`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]` 
	public 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];

				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();
	}

第二种

	public String multiply(String num1, String num2) {
		if (num1.equals("0") || num2.equals("0"))
			return "0";
		int n1 = num1.length();
		int n2 = num2.length();
		int[] products = new int[n1 + n2];
		for (int i = n1 - 1; i >= 0; i--) {
			for (int j = n2 - 1; j >= 0; j--) {
				products[i + j + 1] += ((int) num1.charAt(i) - '0') * ((int) num2.charAt(j) - '0');
			}
		}
		int carry = 0;
		StringBuilder sb = new StringBuilder();
		for (int i = n1 + n2 - 1; i >= 0; i--) {
			int tmp = products[i] + carry;
			sb.append(tmp % 10);
			carry = tmp / 10;
		}
		sb.reverse();
		if (sb.charAt(0) == '0')
			sb.deleteCharAt(0);
		return sb.toString();

	}



你可能感兴趣的:(leetcode)