Add Tow Numbers

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.

思路:

因為兩個數字都是倒序儲存的,所以直接送鏈表的開頭逐個相加即可,但是需要注意的是,當整個循環結束后,可能進位不是0,所以要把進位加到結果中去,這是一個比較重要的臨界條件。

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;  //缺少的位用零補上
    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,否則可能出現NullPointerException
    if(l2 != null) l2 = l2.next;
  }
  if(carry != 0){   //如果還有進位就加到結果的最后
    cur.next = new ListNode(carry);
  }
  return head.next;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容