My not-simple and not-clever Java solution


  • 0
    P

    Part I : will solve the given example [2,4,3] + [5,6,4] = [7,0,8].

    Part II : will solve something like [1] + [9] = [0,1] not [0].

    Part III: will solve something like [1] + [2,3,4,5] = [3,3,4,5].

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	
    	ListNode dum = new ListNode(99);
    	ListNode p0 = dum;
    	ListNode p1 = l1;
    	ListNode p2 = l2;
    	int overflow = 0;
    	
    	while(p1 != null || p2 != null){
    		
    		// Part III
    		if(p1 == null && p2 != null){
    			p1 = new ListNode(0);
    		}else if(p1 != null && p2 == null){
    			p2 = new ListNode(0);
    		}
    		
    		// Part I
    		if(p1.val+p2.val+overflow < 10){	// The +oveflow bit is for something like: [9,9] + [1] = [0,0,1] not [0,10]
    			ListNode temp = new ListNode(p1.val+p2.val + overflow);
    			p0.next = temp;
    			p0 = p0.next;
    			overflow = 0;
    		}else{
    			ListNode temp = new ListNode( (p1.val+p2.val + overflow)%10 );
    			p0.next = temp;
    			p0 = p0.next;
    			overflow = 1;
    		}
    	
    		p1 = p1.next;
    		p2 = p2.next;
    	}
        
    	// Part II
    	if(overflow == 1){
    		ListNode temp = new ListNode(overflow);
    		p0.next = temp;
    	}
    	return dum.next;
    }

Log in to reply
 

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