leetcode_2_Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution

Approach 1: Elementary Math 初等数学

Intuition

Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.

使用变量跟踪进位并从列表头部开始模拟逐位数字,其中包含最低有效数字。

 

 

Algorithm

Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of l1 and l2. Since each digit is in the range of 0…9, summing two digits may "overflow". For example 5 + 7 = 12. In this case, we set the current digit to 2 and bring over the carry = 1 to the next iteration. carry must be either 0or 1 because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 19.

就像你在一张纸上总和两个数字一样,我们首先将最低有效数字相加,即l1和l2的头部。 由于每个数字在0 ... 9的范围内,因此对两个数字求和可能会“溢出”。 例如,5 + 7 = 12.在这种情况下,我们将当前数字设置为2并将carry = 1移至下一次迭代。 carry必须是0或1,因为两位数的最大可能总和(包括进位)是9 + 9 + 1 = 19。

The pseudocode is as following:

  • Initialize current node to dummy head of the returning list.
  • Initialize carry to 0.
  • Initialize p and q to head of l1 and l2 respectively.
  • Loop through lists l1 and l2 until you reach both ends.
    • Set x to node p's value. If p has reached the end of l1, set to 0.
    • Set y to node q's value. If q has reached the end of l2, set to 0.
    • Set sum = x + y + carry.
    • Update carry = sum / 10.
    • Create a new node with the digit value of (sum mod 10) and set it to current node's next, then advance current node to next.
    • Advance both p and q.
  • Check if carry = 1, if so append a new node with digit 1 to the returning list.
  • Return dummy head's next node.

伪代码如下:

将当前节点初始化为返回列表的虚拟头。
初始化进位为0。
将p和q分别初始化为l1和l2的头部。
循环列出l1和l2,直到达到两端。
将x设置为节点p的值。 如果p已达到l1的末尾,则设置为0。
将y设置为节点q的值。 如果q已达到l2的末尾,则设置为0。
设置sum = x + y + carry。
更新carry = sum / 10。
创建一个数值为(sum mod 10)的新节点,然后将其设置为当前节点的下一个节点,然后将当前节点前进到下一个节点。
推进p和q。
检查carry = 1,如果是,则将带有数字1的新节点附加到返回列表中。
返回虚拟头的下一个节点。

Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head's value.

请注意,我们使用虚拟头来简化代码。 如果没有虚拟头,则必须编写额外的条件语句来初始化头部的值。

Take extra caution of the following cases(请特别注意以下情况):

Test caseExplanation
l1=[0,1]
l2=[0,1,2]
When one list is longer than the other.     当一个列表比另一个列表长时。
l1=[]
l2=[0,1]
When one list is null, which means an empty list.  当一个列表为空时,表示空列表。
l1=[9,9]
l2=[1]
The sum could have an extra carry of one at the end, which is easy to forget.  总和可能会在最后有一个额外的一,这很容易忘记。

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while(p != null || q != null){
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum%10);
            curr = curr.next;
            if(p != null) p = p.next;
            if(q != null) q = q.next;
        }
        if(carry > 0){
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值