(LeetCode) Add Two Numbers

https://leetcode.com/problems/add-two-numbers/description/

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.


题目是给定两个非空倒叙排列的链表,要求将两个链表相加形成一个新的链表。新的链表同样是倒叙排列。如2-4-3 + 5-6-4, 即为342+465 = 708 , 所得链表需要为8-0-7.

本题不用考虑倒序问题,因为正着加和反着加结果是一样的,结果所得链表也为倒序。

/**
 * 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) {
            int sum = 0;
            ListNode temp = new ListNode(0);//初始化新链表,用于操作
            ListNode temp1 = temp;//保存新链表头部,用于返回。
            while (l1 != null || l2 != null) {
                sum /= 10;//处理进位问题
                if (null != l1) {//相加
                    sum += l1.val;
                    l1 = l1.next;
                }
                if (null != l2) {
                    sum += l2.val;
                    l2 = l2.next;
                }

                temp.next = new ListNode(sum % 10);//保存相加结果的个位数
                temp = temp.next;
            }
            if(sum/10 == 1)//如果此时一个链表已经为空,即两个链表长度不同,则需要处理最后一位的问题。(如倒数第二位进位为9,最后一个链表末尾数为9,则9+9=18,进位1,放到最后一位)
                temp.next = new ListNode(1);
            return temp1.next;//从temp的next开始返回
    }
}
放一个相似解法,和上面区别不大
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode head = new ListNode(0);
    ListNode result = head;
    int carry = 0;
    
    while (l1 != null || l2 != null || carry > 0) {
        int resVal = (l1 != null? l1.val : 0) + (l2 != null? l2.val : 0) + carry;
        result.next = new ListNode(resVal % 10);
        carry = resVal / 10;
        l1 = (l1 == null ? l1 : l1.next);
        l2 = (l2 == null ? l2 : l2.next);
        result = result.next;
    }
    
    return head.next;
}

猜你喜欢

转载自blog.csdn.net/zhouy1989/article/details/79641843