Skip to content

Latest commit

 

History

History
36 lines (29 loc) · 843 Bytes

File metadata and controls

36 lines (29 loc) · 843 Bytes

2. Add Two Numbers

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

tag:

  • linked list

Solution

链表模拟加法操作,高位补零简化代码 java

	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		int carry = 0, res = 0;
		ListNode dummy = new ListNode(0);
		ListNode p = dummy;
		while (l1 != null || l2 != null || carry!=0) {
			res = ((l1==null)?0:l1.val) + ((l2==null)?0:l2.val) + carry;
			carry = res / 10;
			p.next = new ListNode(res % 10);
			p = p.next;
			l1 = (l1==null)?l1:l1.next;
			l2 = (l2==null)?l2:l2.next;
		}
		return dummy.next;
	}

go