2.Add Two Numbers
来源:互联网 发布:入驻阿里云大厦的条件 编辑:程序博客网 时间:2024/06/06 09:07
Problem
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
Solution
Intuition
Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.
Algorithm
Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of l1and l2. Since each digit is in the range of 0…9, summing two digits may “overflow”. For example 5 + 7 = 12. In this case, we set the current digit to 2 and bring over the carry=1 to the next iteration. carry must be either 0 or 1 because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 19。
The pseudocode is as following:
- Initialize current node to dummy head of the returning list.
- Initialize carry to 0.
- Initialize p and q to head of l1 and l2 respectively.
- Loop through lists l1 and l2 until you reach both ends and carry = 0.
- Set x to node p’s value. If p has reached the end of l1, set to 0.
- Set y to node q’s value. If q has reached the end of l2, set to 0.
- Set sum = x + y + carry.
- Update carry = sum / 10.
- Create a new node with the digit value of (sum % 10) and set it to current node’s next, then advance current node to next.
- Advance both p and q.
- Return dummy head’s next node.
Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head’s value.
Take extra caution of the following cases:
/** * 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* dummy = new ListNode(INT_MAX); ListNode *cur = dummy; int carry = 0; while(l1 || l2 || carry) { int sum = (l1?l1->val:0) + (l2?l2->val:0) + carry; carry = sum / 10; ListNode *tmp = new ListNode(sum % 10); cur->next = tmp; cur = cur->next; l1 = l1?l1->next:l1; l2 = l2?l2->next:l2; } return dummy->next; }};
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- TCP的超时与重传
- FFT 入门
- 2016.08.12【初中部 NOIP提高组 】模拟赛C
- 五大步完成JBOSS 5 多数据库的多数据源配置
- Oracle只读权限(12c新特性)
- 2.Add Two Numbers
- ProgressAction
- js秒数格式化
- 【poj1050】 To the Max
- Atiti.大企业病与小企业病 大公司病与小公司病
- Spring Security教程第二部分-工程里添加spring-security
- Spring重点类/标签介绍
- 支付宝9.9是与非
- Vivado自定义IP封装流程