两数相加(Add Two Numbers)

栏目: 数据库 · 发布时间: 4年前

内容简介: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

题目

英文

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.

中文

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

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

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

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 0 -> 8

原因:342 + 465 = 807

解答

按照一般的加法规则计算,从低位往高位进行计算,如果某一位计算超过10就进一(当前为取余),当高位没有的时候,就补0即可。这里已经是逆序排列来,那么直接循环进行计算

Java

case1

public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = null;
        //上一个节点数据的临时保持,方便添加当前节点的结果
        ListNode lastNode = null;
        // 判断上一个节点计算结果是否有进位
        boolean lastNodeHasStepIn = false;

        // 按照加法的计算,同步进位即可,
        while (l1 != null || l2 != null) {
            int curVal = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0);
            // 低位是否有进位
            if (lastNodeHasStepIn) {
                curVal += 1;
                lastNodeHasStepIn = false;
            }

            //判断是否存在进位
            if (curVal >= 10) {
                curVal = curVal % 10;
                lastNodeHasStepIn = true;
            }

            ListNode currentNode = new ListNode(curVal);
            //todo 可以节省这一步,提升时间效率
            if (result == null) {
                result = currentNode;
            } else {
                lastNode.next = currentNode;
            }
            // 切换Node
            lastNode = currentNode;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }

        if (lastNodeHasStepIn) {
            ListNode next = new ListNode(1);
            result.next = next;
        }

        return result;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

结论: 接受

时间:2 ms(96.54%)

内存:45.8 MB( 56.11%)

分析

上面的算法中,lastNodeHasStepIn 不断判断会增加时间,其中对 result == null 的每一步判断实际上不需要,同样增加了时间,其实只是第一步的时候需要。那么可以进行优化如下:

/**
 * 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) {
        ListNode result = new ListNode(-1);
        //上一个节点数据的临时保持,方便添加当前节点的结果
        ListNode lastNode = result;
        // 上一步的进位为0;默认没有
        int stepIn = 0;

        // 按照加法的计算,同步进位即可,
        while (l1 != null || l2 != null) {
            // 两数同位之后,加上低位的步进
            int curVal = (l1 != null ? l1.val : 0)
                    + (l2 != null ? l2.val : 0)
                    + stepIn;

            //计算是否有步进,强制取整
            stepIn = curVal / 10;
            // 取余获得数值,如果有步进的话
            curVal = curVal % 10;

            lastNode.next = new ListNode(curVal);
            // 切换Node
            lastNode = lastNode.next;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }

        if (stepIn > 0) {
            lastNode.next = new ListNode(stepIn);
        }

        return result.next;

    }
}

结论: 接受

时间:2 ms(96.54%)

内存:45 MB( 61.38% )

好吧时间居然没有减少,倒是内存少了,感觉判断条件对最终结果影响不大,所以我最终改成了如下:

/**
 * 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) {
        ListNode result = null;
        ListNode lastNode = null;
        int stepIn = 0;

        while (l1 != null || l2 != null) {
            int curVal = (l1 != null ? l1.val : 0)
                    + (l2 != null ? l2.val : 0)
                    + stepIn;

            stepIn = curVal / 10;
            curVal = curVal % 10;

            ListNode curNode = new ListNode(curVal);
            if (result != null) {
                lastNode.next = curNode;

            } else {
                result = curNode;
            }

            lastNode = curNode;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }

        if (stepIn > 0) {
            lastNode.next = new ListNode(stepIn);
        }

        return result;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to the Design and Analysis of Algorithms

Introduction to the Design and Analysis of Algorithms

Anany Levitin / Addison Wesley / 2011-10-10 / USD 117.00

Based on a new classification of algorithm design techniques and a clear delineation of analysis methods, Introduction to the Design and Analysis of Algorithms presents the subject in a coherent a......一起来看看 《Introduction to the Design and Analysis of Algorithms》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具