method1:
链表,设置尾指针,从低位计算,达到标志是就停止
#include <iostream>
#include <string>
using namespace std;
struct ListNode {
int val;
ListNode* left;
ListNode(int a):val(a),left(NULL){}
};
typedef ListNode* _tr;
int main() {
string s1,s2;
cin>>s1>>s2;
int len1 = s1.size(),len2 = s2.size();
_tr h1=new ListNode(-1); _tr h2=new ListNode(-1);
for (int i=0;i<len1;i++) {
_tr tmp=new ListNode(s1[i]-'0');
tmp->left = h1;
h1 = tmp;
}
for (int i=0;i<len2;i++) {
_tr tmp = new ListNode(s2[i]-'0');
tmp->left = h2;
h2 = tmp;
}
_tr h3=new ListNode(-1);
int c = 0;
int temp;
while (h1->val!=-1||h2->val!=-1) {
if (h1->val!=-1&&h2->val!=-1) {
temp = (c+h1->val+h2->val)%10;
c= (c+h1->val+h2->val)/10;
}
if (h1->val==-1&&h2->val!=-1) {
temp = (c+h2->val)%10;
c= (c+h2->val)/10;
}
if (h1->val!=-1&&h2->val==-1) {
temp = (c+h1->val)%10;
c= (c+h1->val)/10;
}
_tr kk=new ListNode(temp);
kk->left = h3;
h3 = kk;
if (h1->val!=-1) h1 = h1->left;
if (h2->val!=-1) h2 = h2->left;
}
if (c!=0) {
temp = c;
_tr kk=new ListNode(temp);
kk->left = h3;
h3 = kk;
}
while (h3->val!=-1) {
cout<<h3->val;
h3 = h3->left;
}
}
method 2:
数组计算,先将数组翻转计算低位的值,并设立哨兵,达到哨兵后分情况讨论,最后在反向输出
// Problem#: 19341
// Submission#: 4844144
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
const int maxn =500;
string a,b;
int ans[maxn];
int main() {
cin>>a>>b;
memset(ans,0,sizeof(ans));
int c=0;
int l1=a.size();
int l2=b.size();
for (int i=0,j=l1-1;i<=j;i++,j--) {
swap(a[i],a[j]);
}
for (int i=0,j=l2-1;i<=j;i++,j--) {
swap(b[i],b[j]);
}
int _max=max(l1,l2);
int _min=min(l1,l2);
for (int i=0;i<_max;i++) {
if (i<_min) {
ans[i] = (a[i]-'0'+b[i]-'0'+c)%10;
c=(a[i]-'0'+b[i]-'0'+c)/10;
}
if (i>=_min) {
if(l1>l2) {
ans[i] = (a[i]-'0'+c)%10;
c=(a[i]-'0'+c)/10;
}
else {
ans[i] = (b[i]-'0'+c)%10;
c=(b[i]-'0'+c)/10;
}
}
}
if (c!=0) {
ans[_max]=c;
for (int i =_max;i>=0;i--) cout<<ans[i];
} else {
for (int i =_max-1;i>=0;i--) cout<<ans[i];
}
}