My Java solution


  • 0
    L

    ...
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode head = null;
        ListNode cur=null;
        ListNode carry = new ListNode(0);
    
        while(l1 != null | l2 != null  ){
    
            if(l1 == null){
                l1 = new ListNode(0);
            } else if(l2 ==null){
                l2 = new ListNode(0);
            }
            int sum = l1.val + l2.val+ carry.val;
            int tenthN = sum/10;
            int digit = sum % 10;
          
     
            if(head ==null){
                head = new ListNode(digit);
                cur = head;
            }else if(cur.next ==null){
                cur.next = new ListNode(digit);
                cur =cur.next;
            }
            
    
    
            
            if( tenthN >= 1 ){
                carry.next= new ListNode(tenthN);
            }else{
                carry.next= new ListNode(0);
                
            }
        
         
            carry = carry.next;
    
        
        
            l1 = l1.next;
            l2 = l2.next;
        }
     
     if(carry.val != 0){
         cur.next = new ListNode(carry.val);
     }
        return head;
    }
    

    }
    ...


Log in to reply
 

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