Description:
You are give two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain leading zero, except the number 0 itself.
思路:
因?yàn)閮蓚€(gè)數(shù)字都是倒序儲存的,所以直接送鏈表的開頭逐個(gè)相加即可,但是需要注意的是,當(dāng)整個(gè)循環(huán)結(jié)束后,可能進(jìn)位不是0,所以要把進(jìn)位加到結(jié)果中去,這是一個(gè)比較重要的臨界條件。
Solution:
public static ListNode add_tow_numbers(ListNode l1, ListNode l2){
ListNode head = new ListNode(0);
ListNode cur = head;
int carry = 0;
while(l1 != null || l2 != null){
int x = (l1 != null) ? l1.val : 0; //缺少的位用零補(bǔ)上
int y = (l2 != null) ? l2.val : 0;
int sum = x + y + carry;
carry = sum / 10;
cur.next = new ListNode(sum %= 10);
cur = cur.next;
if(l1 != null) l1 = l1.next; //先判斷是不是null,否則可能出現(xiàn)NullPointerException
if(l2 != null) l2 = l2.next;
}
if(carry != 0){ //如果還有進(jìn)位就加到結(jié)果的最后
cur.next = new ListNode(carry);
}
return head.next;
}