算法探索_两数相加

问题描述:

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

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

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

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers

解决思路:

1.由于是逆序排列,直接向后进位即可

2.当循环执行完毕,务必判断进位符x是否为1, 这种情况会多一位数,比如:5+5=10,长度由1变成了2。

    /*
     *作者:赵星海
     *时间:2020/8/31 9:39
     *用途:两数相加
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int x = 0;
        ListNode node;
        if (l1.val + l2.val > 9) {
            x = 1;
            node = new ListNode(l1.val + l2.val - 10);
        } else {
            node = new ListNode(l1.val + l2.val);
        }
        ListNode result = node;
        l1 = l1.next;
        l2 = l2.next;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                if (l2.val + x > 9) {
                    node.next = new ListNode(l2.val + x - 10);
                    x = 1;
                } else {
                    node.next = new ListNode(l2.val + x);
                    x = 0;
                }
                node = node.next;
                l2 = l2.next;
                continue;
            }
            if (l2 == null) {
                if (l1.val + x > 9) {
                    node.next = new ListNode(l1.val + x - 10);
                    x = 1;
                } else {
                    node.next = new ListNode(l1.val + x);
                    x = 0;
                }
                node = node.next;
                l1 = l1.next;
                continue;
            }
            if (l1.val + l2.val + x > 9) {
                node.next = new ListNode(l1.val + l2.val + x - 10);
                x = 1;
            } else {
                node.next = new ListNode(l1.val + l2.val + x);
                x = 0;
            }
            node = node.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        if (x == 1) {
            node.next = new ListNode(x);
        }
        return result;
    }

leetCode提交结果:

猜你喜欢

转载自blog.csdn.net/qq_39731011/article/details/108315493
今日推荐