LeetCode算法2:java 两数相加

版权声明:可以转载,请注明链接出处 https://blog.csdn.net/xihuanyuye/article/details/85088645

问题:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

解答:
思路:问题不难,就是注意采用列表求加法,判断进位。这里对判断时进行了一个连续或运算的技巧。

public class _02AddTwoNumbers{

public ListNode addTwoNumbers(ListNode l1,ListNode l2){
	
	ListNode tmp = null;
	ListNode result = null;
	
	int carry = 0;
	while(l1!=null || l2!=null || carry!=0){
		
		int sum = (l1 == null?0:l1.val )+( l2 == null?0:l2.val) + carry;
		carry = sum/10;
		ListNode node = new ListNode(sum%10);
		
		if(tmp == null){
			tmp = node;
			result = tmp;
			if (l1!=null) l1 = l1.next;
			if (l2!=null) l2 = l2.next;			
		}else{
			tmp.next = node;
			tmp = tmp.next;
			if (l1!=null) l1 = l1.next;
			if (l2!=null) l2 = l2.next;	
			}
	}
	
	return result;
	
}

public static void main(String[] args){
	
	_02AddTwoNumbers addtwonumbers = new _02AddTwoNumbers();
	
	ListNode tmp = null;

	ListNode l1 = new ListNode(1);
	tmp = new ListNode(2);
	l1.next  = tmp;
	
	tmp.next = new ListNode(3);
	tmp = tmp.next;
	
	tmp.next = new ListNode(4);
	tmp = tmp.next;
	
	System.out.println("###########l1###########");
	addtwonumbers.getListlength(l1);
	addtwonumbers.readList(l1);
	
	ListNode l2 = new ListNode(1);
	tmp = new ListNode(0);
	l2.next = tmp;
	
	tmp.next = new ListNode(8);
	tmp = tmp.next;
	
	tmp.next = new ListNode(9);
	tmp = tmp.next;
	
	tmp.next = new ListNode(1);
	tmp = tmp.next;
	
	System.out.println("###########l2###########");
	addtwonumbers.readList(l2);
	addtwonumbers.getListlength(l2);
	
	ListNode result = addtwonumbers.addTwoNumbers(l1,l2);
	System.out.println("###########result###########");
	addtwonumbers.readList(result);
	addtwonumbers.getListlength(result);
	
	}

public void readList(ListNode list){
	System.out.println("the list is:");
	if (list == null) return;
	while(list !=null){
		System.out.print(list.val+",");
		list = list.next;
		}
	}
	
	public void getListlength(ListNode list){
		System.out.println("the list length is:");
		int i = 0;
		if (list == null) System.out.println("list length is "+i);
		while(list !=null){
			i++;
			list = list.next;
		}
		System.out.println("list length is "+i);
	}
	

}

class ListNode{
	
	int val;
	ListNode next;
	
	ListNode(int x){
		val = x;
		}
		
	}

猜你喜欢

转载自blog.csdn.net/xihuanyuye/article/details/85088645
今日推荐