LeetCode 43.文字列の乗算(垂直乗算)C ++



Leetcode 43 Multiply Strings C



文字列として表される2つの非負の整数num1とnum2が与えられた場合、これも文字列として表されるnum1とnum2の積を返します。
文字列形式で表現された2つの非負の整数num1とnum2が与えられた場合、num1とnum2の積を返し、それらの積も文字列形式で表現されます。
例1:

Input: num1 = '2', num2 = '3' Output: '6'

例2:



Input: num1 = '123', num2 = '456' Output: '56088'

注意:

num1とnum2の両方の長さは<110.
num1とnum2の両方に、0〜9の数字のみが含まれています。
num1とnum2の両方に、数値0自体を除いて、先行ゼロは含まれていません。
組み込みのBigIntegerライブラリを使用したり、入力を直接整数に変換したりしないでください。
num1とnum2の長さは110未満です。
num1とnum2には、0〜9の数字のみが含まれます。
num1もnum2も、それ自体が0でない限り、ゼロで始まることはありません。
多数のタイプの標準ライブラリ(BigIntegerなど)を使用したり、入力を整数に直接変換して処理したりすることはできません。



class Solution { public: string multiply(string num1, string num2) { int n1=num1.size() int n2=num2.size() string res(n1+n2,'0')//Multiply 2 numbers, the length of the quotient must not be greater than the sum of the lengths of the 2 numbers size1 + size2 for(int i=n1-1i>=0i--){ for(int j=n2-1j>=0j--){ int sum = (num1[i] - '0')*(num2[j] - '0') + (res[i+j+1]-'0') res[i+j+1] = sum % 10 + '0' res[i+j] += sum/10 //Characters in string plus int are automatically converted to char without adding '0' } } //Eliminate leading zero for(int i = 0 i < n1+n2 i++){ if(res[i]!='0'){ return res.substr(i) } } return '0' } }

参照C ++の垂直乗算コードはシンプルでエレガント、そして理解しやすい