LeetCode#43. Multiply Strings

題目:

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.
題意解析:

高精度乘法,就是通過像小學那樣列數式相乘,將每一層得到的數式相加,並獲得最終的結果。

例如333乘55

3 3 3

   5 5

      1 6 6 5

   1 6 6 5

   1 8 3 1 5

通過將每一層得到的數式存起來,再相加就可以得到最終的結果,空餘的地方以0作爲補充。

一種c++的代碼實現如下:

#include<iostream>
#include<string>

using namespace std;
class Solution {
public:
    string multiply(string num1, string num2) {
    	//若有一個數爲0,則立即返回0 
    	if(num1 == "0" || num2 == "0") return "0";
        int n1 = num1.length();
        int n2 = num2.length();
		string *process = new string[n2];
		//結果,和反向結果,爲了表示方便,用反向結果進行運算,將反向結果反向已得到最終的結果 
		string result, invert_result;
		//將num2當做被乘數,則num2有多少位就會得到多少個數式,將其分別保存下來,並做初始化 
		for(int i = 0; i < n2; i++) {
			// 每個數式的長度的定義,由兩個乘數的長度加1確定 
			for(int j = 0; j < n1+n2+1; j++) {
				process[i] += '0';
			}
		}
		//乘法運算 
		for(int i = 0; i < n2; i++) {
			int k = i;
			//進位 
			int carry = 0;
			for(int j = n1-1; j >= 0; j--) {
				//乘數 
				process[i][k++] = ( ( (num2[n2-1-i]-'0')*(num1[j] - '0') ) % 10 + carry ) % 10 + '0';
				//獲得進位 
				carry = ( (num2[n2-1-i]-'0')* (num1[j] - '0') ) / 10 + ( ( (num2[n2-1-i]-'0')*(num1[j] - '0') ) % 10 + carry )/10;
			}
			//最開頭的進位 
			if(carry != 0) process[i][k] = carry+'0';
		}
		int min_num_length = process[n2-1].length();
		/*
		for(int i = 0; i < n2; i++) {
			cout<<process[i]<<endl;
		}
		*/
		//將所有得到的舒適相加,獲得最終的結果 
		if(n2 != 1) {
		for(int j = 0; j < n1+n2; j++) invert_result += '0';
		int carry = 0;
		int last_carry = 0;
		for(int i = 0; i < min_num_length; i++) {
			carry = 0;
			for(int k = 0; k < n2-1; k++) {
				if(k == 0) {
					invert_result[i] = ( (process[k][i]-'0')+(process[k+1][i]-'0') )%10+'0';
					carry += ( (process[k][i]-'0')+(process[k+1][i]-'0') ) / 10;
				} else {
					int old_num = (invert_result[i]-'0');
					invert_result[i] = ( old_num+(process[k+1][i]-'0') )%10+'0';
					carry += ( old_num+(process[k+1][i]-'0') ) / 10;
				}
			}
			if(last_carry != 0) {
				int old_num = (invert_result[i]-'0');
				invert_result[i] = ( (invert_result[i]-'0') + last_carry ) % 10+'0';
				carry += ( old_num+ last_carry ) / 10;
			}
			last_carry = carry;
			//cout<<carry<<" "<<last_carry<<endl;
		}
		} else{
			invert_result += process[0];
		}
		int start = invert_result.length()-1;
		//反向,並將開頭的零去掉 
		while(invert_result[start] == '0') {
			start--;
		}
		for(int i = start; i >= 0; i--) {
			result+= invert_result[i];
		}
		//cout<<result<<endl;
		return result; 
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章