LeetCode415:字符串相加;LeetCode43:字符串相乘(大数问题)

image.png
class Solution {
public:
    /**
    "12" + "9" = "21"
    step1: 2+9 = 11, flag = 11 -> res = "1" -> flag = 1;
    step2: flag = flag + 1 = 2, res = "1" + "2" = "12", flag = 0;
    step3: 跳出while了, reverse : res  21
    */
    string addStrings(string num1, string num2) {
        int flag = 0;//记录进位
        int n1 = num1.size()-1, n2 = num2.size()-1;
        string res = "";
        while(n1 >= 0 || n2 >= 0 || flag != 0) {
            if(n1 >= 0) {
                flag += num1[n1] - '0';
                n1--;
            } 
            if(n2 >= 0) {
                flag += num2[n2] - '0';
                n2--;
            }
            res += to_string(flag % 10);
            flag = flag / 10;
        } 
        reverse(res.begin(), res.end());
        return res;
    }
};
image.png
class Solution {
public:
    /**
    "123" * "12"
        123
    *    18
_____________
         24
        16
        8
         3
        2
       1  
res:  02214 
    */
    string multiply(string num1, string num2) {
        int m = num1.size()-1, n = num2.size()-1;
        vector res(m + n + 2, 0);
        int tmp;
        string str = "";
        for(int i = m; i >= 0; i--) {
            for(int j = n; j >= 0; j--) {
                tmp = (num1[i]-'0') * (num2[j]-'0') + res[i+j+1];
                res[i+j+1] = tmp%10;
                res[i+j] += tmp/10;
            }
        }
        int index = 0;
        while(index < res.size() && res[index] == 0) {
            index++;
        }
        for(;index < res.size(); index++) {
            str += res[index] + '0';
        }
        return str == "" ? "0" : str; 
     }
};

你可能感兴趣的:(LeetCode415:字符串相加;LeetCode43:字符串相乘(大数问题))