2.两数相加

题目:

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

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

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

示例:

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

 

思路:按位相加,大于10则向上进位。

 

代码:

	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode l3 = new ListNode(0);
		int up = 0;
		ListNode templ = l3;
		ListNode tl1 = l1,tl2 = l2;
		while (tl1 != null || tl2 != null) {
			if (tl1 != null && tl2 != null) {
				ListNode l = new ListNode((tl1.val + tl2.val + up) % 10);
				templ.next = l;
				templ = l;
				up = (tl1.val + tl2.val + up) / 10;
				tl1 = tl1.next;
				tl2 = tl2.next;
			}else if(tl1 == null) {
				ListNode l = new ListNode((tl2.val + up) % 10);
				templ.next = l;
				templ = l;
				up = (tl2.val + up) / 10;
				tl2 = tl2.next;
			}else if(tl2 == null) {
				ListNode l = new ListNode((tl1.val + up) % 10);
				templ.next = l;
				templ = l;
				up = (tl1.val + up) / 10;
				tl1 = tl1.next;
			}
		}
		if(up != 0) {
			ListNode l = new ListNode(up);
			templ.next = l;
		}

		return l3.next;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章