[Java] My solution (53 ms)


  • 0
    D

    Hi!


    public ListNode addTwoNumbers(ListNode l1, ListNode l2)
    {
    int sum = 0;
    ListNode head = new ListNode(-1);
    ListNode tail = head;
    ListNode prev = null;

    while (l1 != null || l2 != null || sum != 0)
    {
      if (l1 != null)
      {
        sum += l1.val;
        prev = l1;
        l1 = l1.next;
      }
      else if (sum == 0) 
      {
        tail.next = l2;
        break;
      }
    
      if (l2 != null)
      {
        sum += l2.val;
        l2 = l2.next;
      }
      else if (sum == 0)
      {
        tail.next = prev;
        break;
      }
      
      tail.next = new ListNode(sum % 10);
      tail = tail.next;
      sum = sum / 10;
    }
    
    return head.next;
    

    }


    If you can suggest improvements, please welcome!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.