2. Add Two Numbers
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
题目大意为:
给定两个非空单向链表代表两个非负整数。整数中每一位的数字都逆序存储在链表节点中,求出这两个非负整数的和并将结果中的数字以相同的逆序方式存储在一个单项链表中。可以不考虑数字前面的0。
解题思路:
用LinkList代表整数中每一个数字,模拟加法进位的方式进行求和计算。例如:2 -> 4 -> 3和5 -> 6 -> 4,先计算个位数 2和5的和为7,十位数4和6的和为10,逢十进一,则该位的数字为0,产生一位进位1到百位参与百位的数字求和。那么百位的结果:3 + 4 + 1(这个1就是刚刚十位相加产生的进位)百位计算结果为8,所以最终返回结果 7 -> 0 -> 8
需要考虑大数情况,所以不能直接用int保存每个LinkList对应的值
c++代码
/**
* 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 *res = new ListNode(-1);
ListNode *cur = res;
int carry = 0;
while(l1 || l2) {
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if(l1) {
l1 = l1->next;
}
if(l2) {
l2 = l2->next;
}
}
if(carry)
cur->next = new ListNode(1);
return res->next;
}
};