字符串相加和相乘

class Solution {
public:
    string multiply(string num1, string num2) {
        if (num1 == "0" || num2 == "0") {//乘0得0
            return "0";
        }

        string ans = "0";
        int m = num1.size(), n = num2.size();
        for (int i = n - 1; i >= 0; i--) {
            string curr;
            int add = 0;
            for (int j = n - 1; j > i; j--) {//给乘数补零,相当于给最后的*10,*100等等
                curr.push_back(0);
            }
            int y = num2.at(i) - '0';
            for (int j = m - 1; j >= 0; j--) {//num2的个位开始乘num1
                int x = num1.at(j) - '0';
                int product = x * y + add;
                curr.push_back(product % 10);
                add = product / 10;
            }
            while (add != 0) {
                curr.push_back(add % 10);
                add /= 10;
            }
            reverse(curr.begin(), curr.end());
            for (auto &c : curr) {//恢复为字符串
                c += '0';
            }
            ans = addStrings(ans, curr);
        }
        return ans;
    }


    string addStrings(string& num1,string& num2){
        string ret;
        int len1=num1.size()-1,len2=num2.size()-1,add=0;
        while(len1>=0||len2>=0||add!=0){//这里就是或条件
            int x=len1>=0?num1[len1]-'0':0;//还有数,则x有值,没数了x=0
            int y=len2>=0?num2[len2]-'0':0;
            int sum=x+y+add;
            ret.push_back(sum%10);
            add=sum/10;
            len1--;
            len2--;
        }
        reverse(ret.begin(),ret.end());
        for(auto& x:ret)
        x+='0';
        return ret;
    }
};

你可能感兴趣的:(LeetCode每日一题,算法,开发语言,leetcode)