首页 > 其他 > 详细

【Leetcode】Add Two Numbers

时间:2014-03-20 14:06:08      阅读:384      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
 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 *p1 = l1, *p2 = l2, dummy(-1), *tail = &dummy;
13         int sum = 0, carry = 0;
14         while (p1 != nullptr || p2 != nullptr) {
15             int v1 = p1 == nullptr ? 0 : p1->val;
16             int v2 = p2 == nullptr ? 0 : p2->val;
17             p1 = p1 == nullptr ? nullptr : p1->next;
18             p2 = p2 == nullptr ? nullptr : p2->next;
19 
20             sum = v1 + v2 + carry;
21             tail->next = new ListNode(sum % 10);
22             tail = tail->next;
23             carry = sum / 10;
24         }
25         if (carry > 0) {
26             tail->next = new ListNode(carry);
27             tail = tail->next;
28         }
29         return dummy.next;
30     }
31 };
View Code

Add binary类似,思想与方法完全一样,只是用链表实现,在链表前加哑元素可以使尾插入的代码简化。

【Leetcode】Add Two Numbers,布布扣,bubuko.com

【Leetcode】Add Two Numbers

原文:http://www.cnblogs.com/dengeven/p/3613504.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!