【LeetCode】Multiply Strings

Multiply Strings 
Total Accepted: 2611 Total Submissions: 13742 My Submissions
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.
像这种大数运算,如果不是很熟悉的话,建议从加法开始练习。
在LeetCode/Plus One一文中已有阐述。
如果是乘法,乘法可以转换成加法么,所以可以按位相乘,然后再累加。
num1和num2相乘,乘数的最大位数也就是num1.length()和num2.length()相加再加1。
可以手工模仿一下乘法的过程,大概就明白为什么是这个数了。
Java AC

public class Solution {
    public String multiply(String num1, String num2) {
        if ("".equals(num1.replace("0", ""))
				|| "".equals(num2.replace("0", ""))) {
			return "0";
		}
		int len1 = num1.length();
		int len2 = num2.length();
		char arrayA[];
		char arrayB[];
		arrayA = num1.toCharArray();
		arrayB = num2.toCharArray();
		int column = len1 + len2;
		int result[] = new int[column];
		int k = column;
		for (int i = len2 - 1; i >= 0; i--) {
			k--;
			int tempCol = k;
			int tempArr[] = new int[column];
			int num = arrayB[i] - '0';
			for (int j = len1 - 1; j >= 0; j--) {
				tempArr[tempCol] += (arrayA[j] - '0') * num;
				if (tempArr[tempCol] >= 10) {
					int mod = tempArr[tempCol] / 10;
					tempArr[tempCol] %= 10;
					tempArr[tempCol - 1] += mod;
				}
				tempCol--;
			}
			result = addNum(tempArr, result, column);
		}
		StringBuffer sb = new StringBuffer();
		int i = 0;
		if (result[0] == 0) {
			i = 1;
		}
		for (; i < column; i++) {
			sb.append(result[i]);
		}
		return sb.toString();
	}
	public int[] addNum(int tempArr[], int result[], int column) {
		for (int i = column - 1; i >= 0; i--) {
			result[i] += tempArr[i];
			if (result[i] >= 10) {
				result[i] -= 10;
				result[i - 1] += 1;
			}
		}
		return result;
	}
}

你可能感兴趣的:(【LeetCode】Multiply Strings)