Java solution O(n) time.


  • 1
    S

    Simple java solution. Loops through the lists if at least one of the nodes is not null or the carry is set to one and performs addition.
    Any comments appreciated :)

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        	
        int carry = 0;
        ListNode resultList = new ListNode(0);
        ListNode temp = resultList;
        
        while(l1 != null || l2 != null || carry == 1){
        	
        	int result = 0;
        	
        	if(l1 == null && l2 == null){
        		temp.next = new ListNode(carry);
        		return resultList.next;
        	}
        	if(l1 != null) result += l1.val;
        	if(l2 != null) result += l2.val;
        	result += carry;
        	carry = 0;
        	if(result > 9){
        		carry = 1;
        		result = result - 10;
        	}
        	
        	ListNode node = new ListNode(result);
        	temp.next = node;
        	temp = temp.next;
        	if(l1 != null)
        	l1 = l1.next;
        	if(l2 != null)
        	l2 = l2.next;
        	
        }
        return resultList.next;
        	
        }
    }
    

Log in to reply
 

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