算法2. Add Two Numbers

2. Add Two Numbers

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

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

Example:

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

给你两个装着非负整数的非空链表。每个节点包含一个数字,且数字反着存。把对应位置相加,然后返回一个链表。
你可以假定两个链表开头都不会为0。

/**
 * 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) {
        
    }
}

解:
这是个单链表,只能从头开始遍历,一个数字范围为09,两个相加范围为018,可能存在进位的情况,那么来一个变量记录下前一位相加是否进位即可。以下是代码:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode resultHead= new ListNode(0);// 用于存储结果
    ListNode p = l1, q = l2, curr = resultHead;
    int carry = 0;// 用于记录是否需要进位
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr = curr.next = new ListNode(sum % 10);
        if (p != null)
            p = p.next;
        if (q != null)
            q = q.next;
    }
    if (carry > 0) {// 判断最后一个节点是否需要进位
        curr.next = new ListNode(carry);
    }
    return resultHead.next;
}

你可能感兴趣的:(算法2. Add Two Numbers)