2. 两数相加

题目描述

思路

与989. 数组形式的整数加法的竖式计算方法基本一样。无非是按位相加并且注意进位及某个数组的数加完了的情况。
另外提一嘴,LeetCode的题目把好些边界情况都给去了,这样不好。

Java代码

/**
 * 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) {
        ListNode res = new ListNode();
        ListNode temp = new ListNode();
        temp.next = res;
        int carry = 0;

        while (l1 != null && l2 != null) {
            temp.next.val = l1.val + l2.val + carry;
            if (temp.next.val >= 10) {
                temp.next.val = temp.next.val % 10;
                carry = 1;
            } else {
                carry = 0;
            }
            temp.next.next = new ListNode();
            temp = temp.next;
            l1 = l1.next;
            l2 = l2.next;
        }

        if (l1 == null && l2 == null) {
            if (carry == 1) {
                temp.next.val = 1;
            } else {
                temp.next = null;
            }
        } else if (l1 == null && l2 != null) {
            while (carry == 1 && l2 != null) {
                temp.next.val = l2.val + carry;
                if (temp.next.val >= 10) {
                    temp.next.val = temp.next.val % 10;
                    carry = 1;
                } else {
                    carry = 0;
                }
                temp.next.next = new ListNode();
                temp = temp.next;
                l2 = l2.next;
            }
            if (l2 == null) {
                if (carry == 1) {
                    temp.next.val = 1;
                } else {
                    temp.next = null;
                }
            } else if (carry == 0) {
                temp.next = l2;
            }

        } else if (l1 != null && l2 == null) {
            while (carry == 1 && l1 != null) {
                temp.next.val = l1.val + carry;
                if (temp.next.val >= 10) {
                    temp.next.val = temp.next.val % 10;
                    carry = 1;
                } else {
                    carry = 0;
                }
                temp.next.next = new ListNode();
                temp = temp.next;
                l1 = l1.next;
            }
            if (l1 == null) {
                if (carry == 1) {
                    temp.next.val = 1;
                } else {
                    temp.next = null;
                }
            } else if (carry == 0) {
                temp.next = l1;
            }

        }

        return res;
    }
}

执行用时:2 ms, 在所有 Java 提交中击败了99.91%的用户
内存消耗:38.9 MB, 在所有 Java 提交中击败了30.50%的用户

你可能感兴趣的:(2. 两数相加)