LeetCode 2. Add Two Numbers 两数相加(Java)

题目:

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.

解答:

题目看似是将链表反转后相加,再反向转化为链表。其实就是两个数字的相加过程,将两个数组从低位开始相加直至最高位,最低位相当于链表的头结点,最高位相当于链表的尾结点。

思路:

  1. 首先新建 head 头结点,node 结点表示当前节点。遍历两个链表进行逐位相加
  2. 若 l1和l2的当前相加节点不为0,则相加两个节点的val值及进位 temp值(每位数字取值范围为0-9 , 则两个数字之和可能会出现进位),若某个当前节点为空(两个链表长度不相等)则节点值=0
  3. 逐步遍历结束后,若尾节点相加之和存在进位,则新建节点存储进位 temp 的值
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        head.next = null;
        ListNode node = head;
        int temp=0;
        while(l1!=null || l2!=null) {
            int x = (l1!=null) ? l1.val : 0;
            int y = (l2!=null) ? l2.val : 0;
            int cur = 0;
            int sum = x + y + temp;
            if(sum>9) {
                cur = sum%10;
                temp = sum/10;
            }else {
                cur = sum;
                temp = 0;
            }
            node.next = new ListNode(cur);
            node = node.next;
            if(l1!=null)  l1 = l1.next;
            if(l2!=null)  l2 = l2.next;
        }
        if(temp!=0) {
            node.next = new ListNode(temp);
        }
        return head.next;
    }
}

在起初的两次提交中均出现了考虑不全面导致的错误。

第一次未考虑到两个链表可能会长度不同,比如 l1 长度大于l2 长度,所以当 l2==null 时,l1还需要继续遍历。因此要增加相应的处理
LeetCode 2. Add Two Numbers 两数相加(Java)_第1张图片
第二次提交时,之前是将两个节点对应值相加得 sum 后,在计算 cur 加上进位 temp,这样会导致若最后两个尾节点相加和为9且存在进位 temp=1时,不能得出新的进位 temp 值,出现计算错误。
LeetCode 2. Add Two Numbers 两数相加(Java)_第2张图片
LeetCode 2. Add Two Numbers 两数相加(Java)_第3张图片

你可能感兴趣的:(LeetCode)