欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Add Tow Numbers

程序员文章站 2024-02-29 10:54:58
...

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;
}

转载于:https://www.jianshu.com/p/97c9cf3c2d40