LeetCode0002 两数相加

1 问题描述

给定两个链表,每个链表表示一个非负整数,其各位数字逆序存储在链表的每个节点中。将这两个整数相加,并以相同形式返回一个表示和的链表。

2 错误解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 将l1中数字转换成一个整数
        int n1 = 0, m = 1;
        while(l1 != null){
            n1 += l1.val * m;
            l1 = l1.next;
            m *= 10;
        }

        // 将l2中数字转换成一个整数
        int n2 = 0;
        m = 1;
        while(l2 != null){
            n2 += l2.val * m;
            l2 = l2.next;
            m *= 10;
        }

        // 两数相加
        int sum = n1 + n2;
        
        // 将结果按要求转换成链表
        ListNode head = null, tail = null;
        while(sum != 0){
            if(head == null){
                head = tail = new ListNode();
                tail.val = sum % 10;
                sum /= 10;
            }else{
                tail.next = new ListNode();
                tail = tail.next;
                tail.val = sum % 10;
                sum /= 10;
            }
        }
        if (tail == null) {  // 考虑 0 + 0 == 0 的特殊情况
            tail = new ListNode();
            tail.val = 0;
            tail.next = null;
            head = tail;
        }else {
            tail.next = null;
        }

        return head;
    }
}

错误原因:使用整型变量记录链表所表示的非负整数的值,将两个整数相加,得到的结果再按题目要求转换成链表形式。这种思路虽然很笨,但对于1568个测试用例中的792个都是可行的,但随着测试用例中整数的位数增多,整数变量会超出范围,导致出现错误结果。尝试使用java.math.BigInteger类,但好像也不可行。

 

3 正确解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int sum = 0, carry = 0;
        int m = 0, n = 0;
        ListNode head = null, tail = null;
        while(l1!= null || l2 != null){
            m = l1 == null ? 0 : l1.val;
            n = l2 == null ? 0 : l2.val;
            sum = m + n + carry;

            if (head == null) {
                head = tail = new ListNode(sum % 10);
            }else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
            tail = tail.next;
            tail.next = null;
        }

        return head;
    }
}

posted @ 2021-08-15 20:20  wangmengdx  阅读(57)  评论(0编辑  收藏  举报