Easy JAVA solution


  • 0
    C
    public ListNode addTwoNumbers(ListNode n1, ListNode n2) {
        int carry=0;
        ListNode n3=null;
        ListNode head=null;
        while(n1!=null||n2!=null){
            if(n1!=null){
                carry+=n1.val;
                n1=n1.next;
            }
            if(n2!=null){
                carry+=n2.val;
                n2=n2.next;
            }
            if(n3==null) {
                n3=new ListNode(carry%10);
                head=n3;
            }else{
                n3.next=new ListNode(carry%10);
                n3=n3.next;
            }
            carry/=10;
        }
        if(carry!=0){n3.next=new ListNode(carry);}
        return head;
    }

Log in to reply
 

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