leetcode算法—两数相加 Add Two Numbers

关注微信公众号:CodingTechWork,一起学习进步。
在这里插入图片描述

题目

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.

两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

Example:

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

题解

/**
 * 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) {
        //初始化为0的节点
        ListNode init = new ListNode(0);
        //当前输出节点位置,初始化为initListNode
        ListNode current = init;
        //进位值
        int carry = 0;
        
        while (l1 != null || l2 != null) {
            //l1的当前值
            int x = l1 == null ? 0 : l1.val;
            //l2的当前值
            int y = l2 == null ? 0 : l2.val;

            //包含进位值的每位上的和
            int sum = x + y + carry;
            //进位值为0还是1
            carry = sum / 10;
            //每个位置对应的数相加后的余数
            sum = sum % 10;
            
            //新增节点输出sum
            current.next = new ListNode(sum);
            //输出结果进行移位
            current = current.next;
            
            //l1移位
            if (l1 != null) {
                l1 = l1.next;
            }
            //l2移位
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        //判断最后数相加时,是否有进位,若有进位,则新增结点指向进位;若无,跳过。
        if (carry == 1) {
            current.next = new ListNode(carry);
        }
        
		//返回init初始化结点的下一个结点头部
        return init.next;
    }
}

1. 初始状态
在这里插入图片描述
2. val值叠加
在这里插入图片描述
3. val值叠加
在这里插入图片描述
4. val值叠加
在这里插入图片描述
5. val值叠加
在这里插入图片描述
6. val值叠加
在这里插入图片描述
7. 结果输出
在这里插入图片描述

参考 add two numbers

posted @ 2022-03-10 10:04  Andya_net  阅读(13)  评论(0编辑  收藏  举报  来源