Add Two Numbers
Question:
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.
解法代码
public class LeetCode002 {
public static void main(String[] args) {
ListNode ln1 = new ListNode(2);
ListNode ln2 = new ListNode(4);
ListNode ln3 = new ListNode(3);
ln1.next = ln2;
ln2.next = ln3;
ListNode ln21 = new ListNode(5);
ListNode ln22 = new ListNode(6);
ListNode ln23 = new ListNode(4);
ln21.next = ln22;
ln22.next = ln23;
ListNode ln = addTwoNumbers(ln1, ln21);
System.out.print(ln.val);
while(ln.next != null) {
System.out.print(ln.next.val);
ln = ln.next;
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode re = new ListNode(0);//返回结果取re.next
ListNode p = l1, q = l2, curNode = re;
int carry = 0;//保存进位,值为0或1
while(p != null || q != null) {
int x = (p == null) ? 0 : p.val;//如果没有值则用0替代
int y = (q == null) ? 0 : q.val;
int sum = x + y + carry;
carry = sum/10;
curNode.next = new ListNode(sum%10);
curNode = curNode.next;
if(p != null)
p = p.next;
if(q != null)
q = q.next;
}
if(carry != 0) {//循环结束后,如果进位为1则增加此节点
curNode.next = new ListNode(carry);
}
return re.next;//re头节点的下一个节点作为返回结果的头结点
}
}
Output:
708
Time And Space Complexity
- addTwoNumbers
Time: 假设m,n表示l1,l2的长度,while循环最多执行max(m,n)次
Space: 新链表的长度最大为max(m,n)+2,一个是进位,一个是起始位置节点
Tips
注意以下测试用例
测试用例 | 说明 |
---|---|
l1=[0,1] l2=[0,1,2] |
当一个列表比另一个列表长时。 |
l1=[] l2=[0,1] |
当一个列表为空时,即出现空列表。 |
l1=[9,9] l2=[1] |
求和运算最后可能出现额外的进位,这一点很容易被遗忘 |
l1=[5] l2=[5] |
求和运算最后可能出现额外的进位,这一点很容易被遗忘 |