字符串加法与乘法

//模拟乘法进位操作
string add(string x, string y) {
    reverse(x.begin(), x.end());
    reverse(y.begin(), y.end());
    string ans;
    if (x.empty() && y.empty())return ans;
    int i = 0, j = 0, c = 0;
    while (i != x.size() || j != y.size() || c) {
        if (i != x.size())c += x[i++] - '0';
        if (j != y.size())c += y[j++] - '0';
        ans += c % 10 + '0';
        c /= 10;
    }
    reverse(ans.begin(), ans.end());
    return ans;
}
string multiply(string num1, string num2) {
    if (num1 == "0" || num2 == "0")return "0";
    string ans;
    for (int i = num1.size() - 1; i >= 0; i--) {
        for (int j = num2.size() - 1; j >= 0; j--) {
            int t = (num1[i] - '0') * (num2[j] - '0');
            string ex = to_string(t);
            int wei = num1.size()+ num2.size()-i - j-2;
            while (wei--) {
                ex +='0';
            }
            ans=add(ans, ex);
        }
    }
    int i = 0;
    while (ans[i++] == '0');
    return ans;
}
===================================================================================================================
//链表模拟,数位左低右高
ListNode* addTwoNumbers(ListNode* l1,ListNode* l2){
    if(l1==NULL)return l2;
    if(l2==NULL)return l1;
    ListNode* head=new ListNode(0);
    ListNode* p=head;
    int flag=0;
    while(l1!=NULL || l2!=NULL || flag){
        if(l1!=NULL){
            flag+=l1->val;
            l1=l1->next;
        }
        if(l2!=NULL){
            flag+=l2->val;
            l2=l2->next;
        }
        p->next=new ListNode(flag%10);
        flag/=10;
        p=p->next;              
    }
    return head->next;      
}
//string模拟,数位和正常顺序相反
string addTwoNumbers(string s1,string s2) {
    string ans;
    if (s1.empty() && s2.empty())return ans;
    int i = 0, j = 0,c=0;
    while (i!=s1.size()||j!=s2.size()||c) {
        if (i != s1.size())c += s1[i++] - '0';
        if (j != s2.size())c += s2[j++] - '0';
        ans += c % 10 + '0';
        c /= 10;
    }
    return ans;
}
posted @ 2021-11-18 20:28  Zupernova  阅读(49)  评论(0编辑  收藏  举报