Share my Java O(n) solution,very clean


  • 0
    U
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null){
        	return l2;
        }
        if(l2 == null){
        	return l1;
        }
        
        int carry = 0;
        int temp = 0;
        int digit = 0;
        ListNode first = l1,second = l2,result = l1;
        ListNode tail = result;
        while(first != null || second != null){
        	
        	int num1 = first != null ? first.val : 0;
        	int num2 = second != null ? second.val : 0;
        	
        	temp = ( num1 + num2 + carry) / 10;
        	digit = (carry + num1 + num2 ) % 10;
        	carry = temp;
        	result.val = digit;
        	
        	if(first != null){
        		first = first.next;  
        	}
        	
        	if(second != null){
        		second = second.next;
        	}
        	     		      	
        	if(first == null && second != null){
        		result.next = second;
        	}
        	
        	if(result.next != null){
        		result = result.next;
        	}
        	
        }
        
        if(carry != 0){
        	ListNode header = new ListNode(carry);  
        	result.next = header;
        }
        return tail;
    }
    

    }


Log in to reply
 

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