题2、Add Two Numbers

题2、Add Two Numbers

topic

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Thinking

This question is in the test list, what a mess to figure out the relationship on the line, I was ignorant long time to react.
Also note thatcarryDo not carry to get lost.
There is not forget, given two numbers may not necessarily equal, pay attention to deal with special cases, but not panic, stepped pit much to remember.

Code

I am chicken dish, bigwigs want to see, I do not want to look at it as

public class Add_Two_Numbers {

	public static void main(String[] args) {
		
		ListNode a = new ListNode( 2 );
		ListNode b = new ListNode( 4 );
		ListNode c = new ListNode( 3 );
		
		ListNode d = new ListNode( 5 );
		ListNode e = new ListNode( 6 );
		ListNode f = new ListNode( 7 );
		
		a.next = b;
		b.next = c;
		
		d.next = e;
		e.next = f;
		
		ListNode o = addTwoNumbers( a, d );

		while( o != null ) {
			System.out.print( o.val );
			o = o.next;
		}
			
	}
	
	 public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	        ListNode first = new ListNode(0);
	    	ListNode before = first;
	    	
	    	int up = 0;
	    	
	    	while( l1!=null || l2!=null || up!=0) {
	    		if( l1!=null && l2!=null ) {
	    		    before.next = new ListNode( (l1.val + l2.val + up)%10 );
	    		    up = (l1.val + l2.val + up)/10;
	    		    l1 = l1.next;
	    		    l2 = l2.next;
	    		}else if( l1==null && l2!=null ) {
	    			before.next = new ListNode( (l2.val + up)%10 );
	    		    up = (l2.val + up)/10;
	    		    l2 = l2.next;
	    		}else if( l1!=null && l2==null ) {
	    			before.next = new ListNode( (l1.val + up)%10 );
	    		    up = (l1.val + up)/10;
	    		    l1 = l1.next;
	    		}else if( l1==null && l2==null && up != 0 ) {
	    			before.next = new ListNode( up );
	    			up = 0;
	    		}
	    		
	    		before = before.next;
	    		
	    	}
	    	
			return first.next;
	        
	    }
}
//节点
class ListNode {
	int val;
	ListNode next;
	ListNode(int x) { val = x; }
  }

Published 25 original articles · won praise 0 · Views 132

Guess you like

Origin blog.csdn.net/weixin_45980031/article/details/103465880