Add Two Numbers 解题报告


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

 题意,反向表达,相加之后还是以链表的形式表达。

 

 1 class Solution {
 2 public:
 3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
 4 {
 5 int forw=0;//进位标志
 6 //建立一个新的链表存储答案
 7 ListNode root(0);
 8 ListNode *output=&root;
 9 while(l1||l2)
10 {
11 int v1 = (l1 ? l1->val : 0);
12 int v2 = (l2 ? l2->val : 0);
13 int sum=v1+v2+forw;
14 //检验sum是否为两位数
15 forw=sum/10;
16 sum=sum%10;
17 ListNode *coNode=new ListNode(sum);
18 output->next=coNode;
19 output=coNode;
20 if(l1)l1=l1->next;
21 if(l2)l2=l2->next;
22 }
23 if(forw>0)
24 {
25 ListNode *coNode=new ListNode(forw);
26 output->next=coNode;
27 output=coNode;
28 }
29 return root.next;
30 }
31 };

 

  

 

posted @ 2014-11-25 23:43  老徐Bowie  阅读(116)  评论(0编辑  收藏  举报