Day 6

1.大数加法 (pass)

大数加法
技能:模拟+字符串

1.1解析

在这里插入图片描述

1.2代码

string solve(string s, string t) {
        string ret;//记录结果
        int i=s.size()-1,j=t.size()-1;
        int tmp=0;//进位位
        while(i>=0||j>=0||tmp)
        {
            if(i>=0) tmp+=s[i--]-'0';
            if(j>=0) tmp+=t[j--]-'0';
            ret+=tmp%10+'0';
            tmp/=10;
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }

2.链表相加(二) (pass)

链表相加(二)
技能:模拟、链表

2.1解析

在这里插入图片描述

2.2代码

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head)//头插
    {
        ListNode* newhead=new ListNode(0);
        ListNode* cur=head;
        while(cur)
        {
            ListNode* next=cur->next;
            cur->next=newhead->next;
            newhead->next=cur;
            cur=next;
        }
        cur=newhead->next;
        delete newhead;
        newhead=nullptr;
        return cur;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        //1.逆序
        head1=reverse(head1);
        head2=reverse(head2);
        //2.高精度加法
        ListNode* newhead=new ListNode(0);
        ListNode* prev=newhead;
        ListNode* cur1=head1,*cur2=head2;
        int tmp=0;
        while(cur1||cur2||tmp)
        {
            if(cur1)
            {
                tmp+=cur1->val;
                cur1=cur1->next;
            }
            if(cur2)
            {
                tmp+=cur2->val;
                cur2=cur2->next;
            }
            prev=prev->next=new ListNode(tmp%10);
            tmp/=10;
        }
        cur1=newhead->next;
        delete newhead;
        newhead=nullptr;
        cur1=reverse(cur1);
        return cur1;
    }
};

3.大数乘法 (pass) 无进位相乘相加

大数乘法
技能:字符串

3.1解析

在这里插入图片描述

3.2代码

string solve(string s, string t) {
        reverse(s.begin(),s.end());
        reverse(t.begin(),t.end());
        int m=s.size(),n=t.size();
        vector<int> tmp(n+m);
        //无进位相乘,再相加
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                tmp[i+j]+=(s[i]-'0')*(t[j]-'0');
            }
        }
        //处理进位
        int c=0;//进位位
        string ret;
        for(auto& x:tmp)
        {
            c+=x;
            ret+=c%10+'0';
            c/=10;
        }
        while(c)
        {
            ret+=c%10+'0';
            c/=10;
        }
        //处理前导0
        while(ret.size()>1&& ret.back()=='0') ret.pop_back();
        reverse(ret.begin(),ret.end());
        return ret;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值