LeetCode 2. 两数相加 Add Two Numbers

题目描述

给定两个非空链表,表示两个非负整数。 数字以相反的顺序存储,每个节点包含一个数字。 添加两个数字并将其作为链接列表返回。

你可以假设这两个数字不包含任何前导零,除了数字0本身。即不会出现 021 这样的数字

Example:

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

题解

这道题给的数是倒着的,返回的结果也是要倒着的,所以倒着加就行了,进位也是要倒着进。

时间:O(n) 空间:O(n)

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        int tem = 0; //作为中间量保存相加的数值
        ListNode res = new ListNode(-1); // 虚拟头节点
        ListNode l3 = res;
        
        while(l1 != null || l2 != null) {
            
            if (l1 != null) {
                tem += l1.val;
                l1 = l1.next;
            }
            
            if (l2 != null) {
                tem += l2.val;
                l2 = l2.next;
            }
            
            l3.next = new ListNode(tem%10);
            tem = tem / 10; //保存进位,tem 只会等于 1 或 0
            l3 = l3.next;
        }
        
        if (tem == 1) {
            l3.next = new ListNode(1); //最后可能还会有进位
        }
        
        return res.next;
    }
}
posted @ 2019-08-14 10:27  丶沧月  阅读(86)  评论(0)    收藏  举报