Day 6
目录
- 1.大数加法 (pass)
- 1.1解析
- 1.2代码
- 2.链表相加(二) (pass)
- 2.1解析
- 2.2代码
- 3.大数乘法 (pass) 无进位相乘相加
- 3.1解析
- 3.2代码
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;
}