My solution in Java


  • 0
    H

    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    if (l1 == null || l2 == null) {
    return null;
    }
    ListNode head = null;
    ListNode tail = null;
    int carry = 0;
    while (l1 != null || l2 != null || carry != 0) {
    int sum = 0;
    if (l1 != null) {
    sum += l1.val;
    }
    if (l2 != null) {
    sum += l2.val;
    }
    sum += carry;
    int val = sum % 10;
    ListNode node = new ListNode(val);
    if (head == null) {
    tail = node;
    head = tail;
    } else {
    tail.next = node;
    tail = tail.next;
    }
    carry = sum / 10;
    if (l1 != null) {
    l1 = l1.next;
    }
    if (l2 != null) {
    l2 = l2.next;
    }
    }
    return head;
    }
    }


Log in to reply
 

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