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:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
常规做法
设置变量isOverflow判断是否要进位
先计算两个list的个位数和, x = l1->val, y = l2->val
加起来, tmp = x + y
若tmp > 9 说明要进位, isOverflow设为true, 并new一个新的ListNode(tmp)
否则, 直接new新的ListNode(tmp)
最后, 更新x, y的值, 更新ListNode(tmp)将要插入的位置
在计算十位数的和, tmp = x + y + ?
其中若前面产生进位, ?
为1, 否则为0
以此类推直至两个list遍历到nullptr,并且isOverflow为false
1 | /** |