My Java solution --beats 93%


  • 0
    C

    public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;        
    
        ListNode result = new ListNode(0);
        ListNode head = result;
        int tmp = 0;
        while(l1 != null || l2 != null){
            int sum = tmp;
            
            if(l1 != null){
                sum += l1.val;
                l1 = l1.next;
            }
            
            if(l2 != null){
                sum += l2.val;
                l2 = l2.next;
            }
            
            if(sum >= 10){
                sum %= 10;
                tmp = 1;
            }
            else
                tmp = 0;
                
                result.next = new ListNode(sum);
                result = result.next;
        }
        
        if(tmp > 0){
            result.next = new ListNode(tmp);
        }
        
        return head.next;
    }
    

    }


Log in to reply
 

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