剑指offer--字符串相加和相乘

leetcode 415 字符串相加–>若直接转为数字进行相加,有可能会造成溢出。
模拟相加的核心代码:

 		int carry = 0; //进位
        for(int i = n1-1; i >= 0; i--){
            int tmp = num1[i] - '0' + num2[i] - '0' + carry; //这一位相加
            num1[i] = tmp%10 + '0';
            carry = tmp/10; //计算进位
        }
class Solution {
public:
    string addStrings(string num1, string num2) {
        int n1 = num1.size();
        int n2 = num2.size();
        //补成等长
        while(n1 < n2){
            num1 = "0" + num1;
            n1++;
        }
        while(n1 > n2){
            num2 = "0" + num2;
            n2++;
        }
        int carry = 0; //进位
        for(int i = n1-1; i >= 0; i--){
            int tmp = num1[i] - '0' + num2[i] - '0' + carry;
            num1[i] = tmp%10 + '0';
            carry = tmp/10;
        }
        if(carry == 1){
            num1 = "1" + num1;
        }
        return num1;
    }
};

leetcode 66 加一,原题目是数字数组加一,我改成字符串加一来练习。

string addOne(string s){
    int carry = 0;
    for(int i = s.size()-1; i >= 0; i--){
        int t = s[i] - '0' + 1;
        s[i] = t%10 + '0';
        carry = t/10;
        if(carry == 0){
            break;
        }
    }
    //"999"
    if(carry == 1){
        s = "1" + s;
    }
    return s;
}
int main()
{   
    string s;
    cin>>s;
    cout<<addOne(s)<<endl;
    return 0;
}

leetcode 415 字符串相乘
剑指offer--字符串相加和相乘_第1张图片

class Solution {
public:
    string multiply(string num1, string num2) {
        int m = num1.size();
        int n = num2.size();
        string res(m+n,'0');
        for(int i = n-1; i >= 0; i--){
            for(int j = m-1; j >= 0; j--){
                int t = res[i+j+1]-'0' + (num2[i] - '0')*(num1[j] - '0');
                res[i+j+1] = t%10 + '0';//当前位
                res[i+j] = res[i+j] - '0' + t/10 + '0'; //进位
            }
        }
        for(int i = 0; i < res.size(); i++){
            if(res[i] != '0'){
                return res.substr(i);
            }
        }
        return "0";
    }
};

你可能感兴趣的:(剑指offer)