0
点赞
收藏
分享

微信扫一扫

金仓数据库kca、kcp模拟题(一)

独西楼Q 2023-08-10 阅读 23

目录

一、题目

二、代码


一、题目

43. 字符串相乘 - 力扣(LeetCode)

二、代码

  

class Solution {
public:
string addStrings(string num1, string num2)//求两个字符串相加
{
    int end1 = num1.size() - 1;
    int end2 = num2.size() - 1;
    int next = 0;//进位
    string s;
    while (end1 >= 0 || end2 >= 0)
    {
        int x1 = end1 >= 0 ? num1[end1] - '0' : 0;
        int x2 = end2 >= 0 ? num2[end2] - '0' : 0;
        int ret = x1 + x2 + next;
        next = ret / 10;
        int y = ret % 10;
        s.insert(0, 1, '0' + y);
        end1--;
        end2--;
    }

    if (next == 1)//像‘9’+‘1’这种情况,剩下一个进位
    {
        s.insert(0, 1, '0' + next);
    }
    return s;
}

string multiply_1(string s_1, char ch)//求一个字符串和一个字符相乘
{
    int next = 0;
    int end1 = s_1.size() - 1;
    string s;
    while (end1 >= 0)
    {
        int x = s_1[end1] - '0';
        int y = ch - '0';
        int ret = x * y + next;
        next = ret / 10;
        int ret2 = ret % 10;
        s.insert(0, 1, '0' + ret2);
        end1--;
    }
    if (next != 0)
    {
        s.insert(0, 1, '0' + next);
    }
    return s;

}
string multiply(string num1, string num2)
{
    if (num1 == "0" && num2 == "0")
    {
        return num1;
    }

    if (num1 == "0" || num2 == "0")
    {
        return num1 == "0" ? num1 : num2;
    }

    int end1 = num1.size() - 1;
    int end2 = num2.size() - 1;
    if (end2 > end1)//保证num1比num2长
    {
        swap(num1, num2);
        swap(end1, end2);
    }
    string ss;
    string s1;
    int k = 0;

    while (end2 >= 0)
    {
        s1 = multiply_1(num1, num2[end2]);
        if (k != 0)
        {
            int j = k;
            while (j--)
            {
                s1.insert(s1.size(), 1, '0');
            }
        }
        k++;
        end2--;
        ss = addStrings(ss, s1);

    }

    return ss;
}
};
举报

相关推荐

0 条评论