Punch tenth day: two numbers together


I, entitled


We are given two non-empty list is used to represent two non-negative integer. Where their respective bits are stored in reverse order of the way, and they each node can store only one digit.

If we add up these two numbers, it will return a new list and to represent them.

You can assume that in addition to the numbers 0, these two numbers will not begin with 0.

Example:

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

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/add-two-numbers
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.


Second, code implementation


Ideas : the use of variables to track the carry, and from the group consisting of the least significant bit header start simulation added bit by bit

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;   //如果p未达到末尾,将p的值赋给x;否则把0赋给x
        int y = (q != null) ? q.val : 0;   //如果q未达到末尾,将q的值赋给y;否则将0赋给y
        int sum = carry + x + y;
        carry = sum / 10;   // 更新carry的值
        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(1);
    }
    return dummyHead.next;
    }
}

The results:
Here Insert Picture Description
time complexity: O (max (m, n )), where m, n are the lengths l1 and l2 of the
complexity of space: O (max (m, n )), the length of the new list at most max ( m, n) +1


Third, the harvest


That the need to pay particular attention to the following:
(1) a list longer than the other list
(2) a list is empty, an empty list appears
(3) carry additional final summation occurs

Secondly, in the programming process, I have developed a special assignment statement
int x = (p = null!
) P.val: 0;? Means that if the value of p is not empty, then assign x p.val , contrary to x 0 then

Published 10 original articles · won praise 0 · Views 121

Guess you like

Origin blog.csdn.net/qq_45400247/article/details/104783485