Share my concise Java solution, very easy to understand!!


  • 0
    V
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int sign=0, sum=0;
        ListNode index1=l1, index2=l2, newHead=new ListNode(-1), node= newHead;
        newHead.next=null;
        while(l1!=null || l2!=null){
            sum=sign;
            if(l1!=null){
                sum+=l1.val;
                l1=l1.next;
            } 
            if(l2!=null){
                 sum+=l2.val;
                 l2=l2.next;
            }
            if(sum >= 10){
                sum=sum%10;
                sign=1;
            }else sign=0;
            node.next=new ListNode(sum);
            node=node.next;
        }
        if(sign!=0) {
            node.next=new ListNode(sign);
        }
        return newHead.next;
    }

Log in to reply
 

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