My Java solution, easy to understand, 4ms


  • 5
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode fake = new ListNode(0);
        ListNode t=fake, t1=l1, t2=l2;
        int a1, a2, r = 0;
        while (t1!=null || t2!=null || r!=0) {
            a1 = t1==null ? 0:t1.val;
            a2 = t2==null ? 0:t2.val;
            r += a1 + a2;
            t.next = new ListNode(r%10);
            r /= 10;
            t = t.next;
            if (t1!=null) t1 = t1.next;
            if (t2!=null) t2 = t2.next;
        }
        return fake.next;
    }
    

    }


  • 0
    X
    This post is deleted!

  • 0
    P

    @simkieu Is ListNode a class/ return type in Java 8? I did not find it. Thanks!


Log in to reply
 

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