【27】2. Add Two Numbers

2. Add Two Numbers

  • Total Accepted: 241470
  • Total Submissions: 910015
  • Difficulty: Medium
  • Contributors: Admin 

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
12         ListNode* dummy = new ListNode(-1);
13         ListNode* tmp = dummy;
14         int carry = 0;//carry要写在最外面 因为算value要加上去 但是第一步要算为0
15         
16         //while(l1 && l2){//分开写的话 l1,l2只有一个节点5的情况下 只会输出一个0 而不是0->1
17         
18         while(l1 || l2){//此时需要判断l1和l2 谁真谁假
19             
20             int n1 = l1 ? l1 -> val : 0;
21             int n2 = l2 ? l2 -> val : 0;
22         
23             //int value = l1 -> val + l2 -> val + carry;
24             int value = n1 + n2 + carry;
25             carry = value / 10;//因为每个节点的都在10以内所以只可能和是两位数 所以不用while循环(value >= 10)
26             
27             ListNode* cur = new ListNode(value % 10);
28             tmp -> next = cur;
29             tmp = tmp -> next;
30             
31             //l1 = l1 -> next;
32             //l2 = l2 -> next;//因为while循环的条件用的||,所以此时也需要判断
33             
34             if(l1){
35                 l1 = l1 -> next;
36             }
37             if(l2){
38                 l2 = l2 -> next;
39             }
40             
41         }
42         /*//用||把一条链长一条链短的情况包含了
43         if(l1){
44             tmp -> next = l1;
45         }
46         if(l2){
47             tmp -> next = l2;
48         }*/
49         
50         if(carry){
51             tmp -> next = new ListNode(carry);
52         }
53         
54         return dummy -> next;
55     }
56 };

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2017-02-08 07:08  会咬人的兔子  阅读(177)  评论(0编辑  收藏  举报