leetcode2两数相加

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

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

示例 1:

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.

示例 2:

输入:l1 = [0], l2 = [0]
输出:[0]

示例 3:

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

提示:

package leetcode;

public class AddTwoNumber_2 {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode now = head;
        int add = 0;
        while (l1 != null || l2 != null) {
            int v1 = 0;
            int v2 = 0;
            if (l1 != null) {
                v1 = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                v2 = l2.val;
                l2 = l2.next;
            }
            int sum = v1 + v2 + add;
            if (sum >= 10) {
                add = 1;
                sum -= 10;
            } else {
                add = 0;
            }
            ListNode child = new ListNode(sum);
            now.next = child;
            now = now.next;
        }
        if (add != 0) {
            ListNode child = new ListNode(add);
            now.next = child;
        }
        return head.next;
    }

    public static void main(String[] args) {
        AddTwoNumber_2 addTwoNumber_2 = new AddTwoNumber_2();
        ListNode listNode11 = new ListNode(9);
        ListNode listNode12 = new ListNode(9, listNode11);
        ListNode listNode13 = new ListNode(9, listNode12);

        ListNode listNode21 = new ListNode(9);
        ListNode listNode22 = new ListNode(9, listNode21);
        ListNode listNode23 = new ListNode(9, listNode22);
        ListNode listNode = addTwoNumber_2.addTwoNumbers(listNode13, listNode22);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }
}
展开阅读全文

页面更新:2024-03-31

标签:逆序   整数   节点   示例   开头   个数   形式   提示   两个   数字

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top