思想:
注意细节。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
string ListToString(ListNode *l) {
if(l == NULL) return "0";
string s;
while(l != NULL) {
s.push_back(l->val+'0');
l = l->next;
}
return s;
}
ListNode* StringToListNode(string s) {
ListNode *l, *head;
for(int i = 0; i < s.size(); i++) {
if(i == 0) {
int val = s[i]-'0';
head = new ListNode(val);
l =head;
}
else {
ListNode *node = new ListNode(s[i]-'0');
head->next = node;
head = head->next;
}
}
head->next = NULL;
return l;
}
//Add Two Numbers
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
string s1 = ListToString(l1);
string s2 = ListToString(l2);
if(s1 == "0" && s2 == "0") {
ListNode *l = new ListNode(0);
return l;
} else if(s1 == "0") {
return StringToListNode(s2);
} else if(s2 == "0") {
return StringToListNode(s1);
}
string s3;
int carry = 0;
int i;
for(i = 0; s1[i]!='\0' && s2[i]!='\0'; i++) {
int sum = s1[i]-'0' + s2[i]-'0' + carry;
s3.push_back(sum%10 + '0');
carry = sum/10;
}
if(s1[i]=='\0') {
while(s2[i]!='\0') {
s3.push_back(((carry+(s2[i]-'0'))%10) + '0');
carry = (carry+(s2[i]-'0'))/10;
i++;
}
} else if(s2[i]=='\0') {
while(s1[i]!='\0') {
s3.push_back(((carry+(s1[i]-'0'))%10) + '0');
carry = (carry+(s1[i]-'0'))/10;
i++;
}
}
if(carry != 0) {
s3.push_back(carry+'0');
}
return StringToListNode(s3);
}
};