43. 字符串相乘C++

    xiaoxiao2022-07-13  167

    从0开始计数,第i位与第j位相乘得到的数就存在结果的第i+j位与第i+j+1位。

    string multiply(string num1, string num2) { int size1 = (int)num1.size(); int size2 = (int)num2.size(); string res(size1+size2,'0'); for (int i = size1-1; i >= 0; --i) { for (int j = size2-1; j >= 0; --j) { int bitRes = (num1[i] - '0') * (num2[j] - '0') + (res[i+j+1]-'0'); res[i + j]= res[i + j]-'0' + (bitRes / 10)+'0'; res[i + j + 1] = (bitRes % 10) +'0'; } } //删除最前面的0 while(res[0] == '0' && res.size()>1) res.erase(0,1); return res; }
    最新回复(0)