美文网首页
2020-11-22 2. Add Two Numbers

2020-11-22 2. Add Two Numbers

作者: _伦_ | 来源:发表于2020-11-22 00:23 被阅读0次

    Medium

    97862459Add to ListShare

    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 contains a single digit. Add the two numbers and return the sum as a linked list.

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

    Example 1:

    Input:l1 = [2,4,3], l2 = [5,6,4]Output:[7,0,8]Explanation:342 + 465 = 807.

    Example 2:

    Input:l1 = [0], l2 = [0]Output:[0]

    Example 3:

    Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]Output:[8,9,9,9,0,0,0,1]

    Constraints:

    The number of nodes in each linked list is in the range [1, 100].

    0 <= Node.val <= 9

    It is guaranteed that the list represents a number that does not have leading zeros.

    /**

    * 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 carry = 0;

            // 结果,当前位

            ListNode res, cur;

            res = cur = new ListNode(0);

            // 两个数的当前位

            ListNode n1 = l1, n2 = l2;

            while (n1 != null || n2 != null || carry != 0) {

                // 当前位数相加,并加上进位

                cur.val = (n1 != null ? n1.val : 0) + (n2 != null ? n2.val : 0) + carry;

                // 清除进位

                carry = 0;

                // 如果当前产生了进位,则位数取个位,然后设置进位

                if (cur.val >= 10) { cur.val -= 10; carry = 1; }

                // 处理下一位

                if (n1 != null) n1 = n1.next;

                if (n2 != null) n2 = n2.next;

                if (n1 != null || n2 != null || carry != 0) cur = cur.next = new ListNode(0);

            }

            return res;

        }

    }

    相关文章

      网友评论

          本文标题:2020-11-22 2. Add Two Numbers

          本文链接:https://www.haomeiwen.com/subject/ytiyiktx.html