You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question
就是遍历,求值,再恢复
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
classSolution{
public:
ListNode*addTwoNumbers(ListNode*l1, ListNode*l2) {
unsignedlonglongsum3= 0;
intcount1= 0;
intcount2= 0;
if(l1==NULL||l2==NULL)
{
returnNULL;
}
while(l1!=NULL)
{
sum3+=pow(10,count1) * (l1->val);
count1++;
l1=l1->next;
}
while(l2!=NULL)
{
sum3+=pow(10,count2) * (l2->val);
count2++;
l2=l2->next;
}
unsignedlongtmp_digit=sum3- (sum3/ 10) * 10;
ListNode*p=newListNode((int)tmp_digit);
ListNode*start=p;
sum3=sum3/ 10;
while(sum3> 0) {
tmp_digit=sum3- (sum3/ 10) * 10;
p->next=newListNode((int)tmp_digit);
p=p->next;
sum3=sum3/ 10;
}
returnstart;
}
};