LeetCode *** 2. Add Two Numbers

来源:互联网 发布:广州茶楼你知多少钱 编辑:程序博客网 时间:2024/06/14 20:23

题目:

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


分析:
一位一位的加,注意要保留进位,同时l1与l2可能位数不一样,也需要注意,大概就这样吧。我RE了很久,我也不知道为啥。。。我到现在都没明白。。我cpp还是忘得差不多了。。心塞。。。

代码:
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {                ListNode *res,*restmp,*l1tmp,*l2tmp;        l1tmp=l1;l2tmp=l2;        int CA=0;        res=new ListNode(0);        restmp=res;                while(l1tmp!=NULL&&l2tmp!=NULL){            int tmp=l1tmp->val+l2tmp->val+CA;            CA=tmp/10;                        restmp->next=new ListNode(tmp%10);            restmp=restmp->next;        //    if(l1->next!=NULL)            l1tmp=l1tmp->next;        //    if(l2->next!=NULL)            l2tmp=l2tmp->next;        }                while(l1tmp!=NULL&&l2tmp==NULL){            int tmp=l1tmp->val+CA;            CA=tmp/10;                        restmp->next=new ListNode(tmp%10);            restmp=restmp->next;                    l1tmp=l1tmp->next;        }                while(l1tmp==NULL&&l2tmp!=NULL){            int tmp=l2tmp->val+CA;            CA=tmp/10;                        restmp->next=new ListNode(tmp%10);            restmp=restmp->next;                        l2tmp=l2tmp->next;        }                if(CA!=0){                        restmp->next=new ListNode(CA);            restmp=restmp->next;                    }                return res->next;    }};

0 0
原创粉丝点击