問題來自leetcode
問題描述
Given two non-negative integers num1 and num2 rePResented as strings, return the product of num1 and num2. Note: The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.
這道題其實挺簡單的,我的想法是對的,但是有冗余的部分,所以記錄一下。
以下是討論區別人分享的代碼
string sum(num1.size() + num2.size(), '0'); for (int i = num1.size() - 1; 0 <= i; --i) { int carry = 0; for (int j = num2.size() - 1; 0 <= j; --j) { int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry; sum[i + j + 1] = tmp % 10 + '0'; carry = tmp / 10; } sum[i] += carry; } size_t startpos = sum.find_first_not_of("0"); if (string::npos != startpos) { return sum.substr(startpos); } return "0";主要思想: 我覺得這個跟加法器很像。Cin是后一位的進位,sum是本位,Cout是進位,out 為本次計算所得的結果。 sum = (out+Cin)%10; Cout = (out+Cin)/10; 遍歷即可得到結果。
新聞熱點
疑難解答