首页 > 代码库 > 2.Add Two Numbers
2.Add Two Numbers
Description:
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
- Difficulty: Medium
简单解释一下题意,两个位置颠倒(例如:892写成298)的数字相加后,按正常顺序输出结果。
解题思路:
1.从左到右开始互加计算,倘若在某位相加和大于等于10,要向右一位加1,而不是左一位加1.
2.题目要求返回的是链表,所以每进位得到的结果可以通过头插法插入到链表首位,最后得到题目要求的正常顺序的结果
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(0);
ListNode* res = head;
int tmp = 0;
while(l1||l2||res){
int num = (l1? l1->val:0) + (l2? l2->val:0) + tmp;
tmp = num / 10;
res->next = new ListNode(num % 10);
res = res->next;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
return head->next;
}
2.Add Two Numbers