Leetcode 4 – Add Two Numbers

Posted on December 22, 2013

Last updated on December 22, 2013

Solution to LeetCode Add Two Numbers problem.

This is just an implementation exercise, no tricky algorithms here.

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  ListNode head = null;
  ListNode cur = null;
  int carry = 0;

  while(l1 != null || l2 != null){

    int value1 = l1 != null ? l1.val : 0;
    int value2 = l2 != null ? l2.val : 0;

    // both non-null
    int val = value1 + value2 + carry;
    int mod = val % 10;
    carry = val / 10;

    ListNode newValue = new ListNode(mod);

    if(head == null){
      head = newValue;
      cur = head;
    }
    else cur.next = newValue;

    cur = newValue;

    l1 = l1 != null ? l1.next : null;
    l2 = l2 != null ? l2.next : null;
  }

  if(carry != 0){
    ListNode c = new ListNode(carry);
    cur.next = c;
  }

  return head;
}
Add Two Numbers
Markdown SHA1: 5f4c87ec4842975d9a9c98d43909375dd5d58dd2