[Daily Practice] - chain adds two numbers

Title Description

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.
The title comes from the leetcode, click into the
list as follows:

public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

Read title

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

Problem-solving

As can be seen from the example, we can see this as a matter of math to calculate. Here it should be noted there are three points:

  • 1, the length of the two lists may be inconsistent
  • 2, there may list is empty
  • 3, extra carry may occur. 99 + 1 = 100 for example

Code

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		// 用于保存相加得到的结果 也用于最终返回 初始化为0
        ListNode retunList = new ListNode(0);
        ListNode p = l1, q = l2, curList = retunList;
        // carry 表示相加超过10后的进位数值
        int carry = 0;
        // 只要有一个链表还有值,那么就要将计算进行下去
        while (p != null || q != null) {
        	// 当链表存在空或者两个链表长度不一致时可能会出现空链表的情况,此时我们用0来与另一个链表相加
            int x = p == null ? 0 : p.val;
            int y = q == null ? 0 : q.val;
            // 计算结果应为链表对应节点的值加上进位的值
            int z = x + y + carry;
            // 重新对进位的值进行赋值
            carry = z / 10;
            // 该节点的值为相加后个位的值 如9 + 5 = 14 那么该位上的值应当为4,1需要进位
            curList.next = new ListNode(z % 10);
            // 对下一个节点进行计算
            curList = curList.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        // 如果最终循环完成后还存在进位的值,应该向上进1位
        if (carry > 0) {
            curList.next = new ListNode(carry);
        }
        // 初始节点为0  所以返回的应该是它的next
        return retunList.next;
    }
Published 26 original articles · won praise 6 · views 2935

Guess you like

Origin blog.csdn.net/weixin_45676630/article/details/105180776