Java: Add Two Numbers


  • 0
    M

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode head=new ListNode(0);
    ListNode copy=head;
    int carry=0;
    int sum=0;
    int v1=0;
    int v2=0;
    while(l1!=null||l2!=null||carry!=0){
    v1=l1==null?0:l1.val;
    v2=l2==null?0:l2.val;
    sum=v1+v2+carry>=10?v1+v2+carry-10:v1+v2+carry;
    copy.next=new ListNode(sum);
    carry=v1+v2+carry>=10?1:0;
    l1=l1==null?l1:l1.next;
    l2=l2==null?l2:l2.next;
    copy=copy.next;
    }
    return head.next;
    }


Log in to reply
 

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