# 题目

2. Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

# 思路

不知道各位能不能看懂题目,简单解释一下,就是把整数每一位颠倒进行加法。题目中给出的例子,最初对应342 + 465 = 807,然后颠倒变成243 + 564 = 708,在转换为链表。

这下题目给出链表的定义,我们需要对这种类型的链表进行操作。

        // Definition for singly-linked list.
        public class ListNode
        {
            public int val;
            public ListNode next;
            public ListNode(int x) { val = x; }
        }

方法一:普通遍历,链表l1和l2相应位置相加,再加进位,存入链表result中。

注意点:

  1. 对于一段长于另外一段的链表部分,单独处理。
  2. 进位。
  3. 结果之和长于两个链表的情况,如1 + 999 = 1000。

普通遍历时间复杂度O(n)空间复杂度O(n)时间204ms

        // normal traversal: time O(n) space O(n) result: 204ms
        public void calculateSum(ListNode tresult, ref int carry, int sum)
        {
            )
            {
                carry = ;
                tresult.next = );
            }
            else
            {
                carry = ;
                tresult.next = new ListNode(sum);
            }
        }

        public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            ListNode tl1 = l1, tl2 = l2;
            ListNode result = );
            ListNode tresult = result;
            ;

            // both ListNode 1 and ListNode 2 have values
            while (tl1 != null && tl2 != null)
            {
                calculateSum(tresult, ref carry, tl1.val + tl2.val + carry);
                tl1 = tl1.next;
                tl2 = tl2.next;
                tresult = tresult.next;
            }

            // Debug.Assert(!(tl1 != null && tl2 != null), "tl1 and tl2 aren't null");
            // either ListNode 1 or ListNode 2 has values (maybe) and don't forget carry.
            while (tl1 != null)
            {
                calculateSum(tresult, ref carry, tl1.val + carry);
                tl1 = tl1.next;
                tresult = tresult.next;
            }
            while (tl2 != null)
            {
                calculateSum(tresult,ref carry, tl2.val + carry);
                tl2 = tl2.next;
                tresult = tresult.next;
            }

            // at this time, ListNode 1 and ListNode 2 should be null, however, carry could be null or not
            // Debug.Assert(tl1 == null && tl2 == null, "calculation doesn't finish");
            ) tresult.next = );

            // neither ListNode 1 nor ListNode 2 have values
            return result.next;
        }
        */

方法二:空间优化遍历,链表l1和l2相应位置相加,再加进位,存入链表l1中。方法二的代码没有方法一的代码清晰。

空间优化遍历时间复杂度O(n)空间复杂度O(1)时间208ms

        // use ListNode 1 to restore result
        // space (and time, I think, but result doesn't prove) optimized traversal: time O(n) space O(1) result: 208ms
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            if (l1 == null) return l2;
            if (l2 == null) return l1;

            , sum = ;
            ListNode pre = null, result = l1;
            )
            {
                // calculate sum and carry
                sum = ;
                if (l1 != null) sum += l1.val;
                if (l2 != null)
                {
                    sum += l2.val;
                    l2 = l2.next; // ListNode1 will be used below, ListNode2 not, so if ListNode 2 next exists, ListNode 2 move to next
                }
                sum += carry;
                )
                {
                    carry = ;
                    sum -= ;
                }
                else
                {
                    carry = ;
                }

                // find a place for sum in ListNode 1, l1 is in use
                if (l1 != null)
                {
                    pre = l1;
                    ) sum -= ;
                    l1.val = sum;
                    l1 = l1.next;
                }
                else
                {
                    ) sum -= ;
                    pre.next = new ListNode(sum);
                    pre = pre.next;
                }

            }
            return result;
        }
        */

方法三:递归,链表l1和l2相应位置相加,再加进位,存入链表node中。速度最快,是比较好的解决方案。

# 解决(递归)

递归时间复杂度O(n)空间复杂度O(n)时间196ms

        // recursive tranversal: time O(n) space:O(n) time: 196ms (why it is faster than normal loop)
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            );
        }

        public ListNode AddTwoNumbers(ListNode l1, ListNode l2, int carry)
        {
            ) return null;

            // calculate sum
            ;
            if (l1 != null) sum += l1.val;
            if (l2 != null) sum += l2.val;
            sum += carry;
            )
            {
                carry = ;
                sum -= ;
            }
            else
            {
                carry = ;
            }

            // set node's next and val and return
            ListNode node = new ListNode(sum);
            node.next = AddTwoNumbers(l1 != null ? l1.next : null, l2 != null ? l2.next : null, carry);
            return node;
        }

# 题外话

为何递归会比循环快呢?百思不得其解,若有高人知道,请指教。

# 测试用例

        static void Main(string[] args)
        {
            _2AddTwoNumbers solution = new _2AddTwoNumbers();
            ListNode l1 = );
            ListNode l2 = );
            ListNode result = );

            // ListNode doesn't have a null constructor, so we can igonore this case
            Debug.Assert(Test.match(solution.AddTwoNumbers(l1, l2), result), "wrong 1");

            // ListNode 1 length is larger than ListNode 2 length
            l1 = );
            l1.next = );
            l1.next.next = );
            l2 = );
            result.next = );
            result.next.next = );
            Debug.Assert(Test.match(solution.AddTwoNumbers(l1, l2), result), "wrong 2");

            // ListNode 2 length is larger than ListNode 1 length and has carries
            l1 = );
            l1.next = );
            l2 = );
            l2.next = );
            l2.next.next = );
            result = );
            result.next = );
            result.next.next = );
            result.next.next.next = );
            Debug.Assert(Test.match(solution.AddTwoNumbers(l1, l2), result), "wrong 3");
        }
  class Test
  {

        public static bool match(_2AddTwoNumbers.ListNode l1, _2AddTwoNumbers.ListNode l2)
        {
            _2AddTwoNumbers.ListNode tl1 = l1, tl2 = l2;
            while(tl1 != null && tl2 != null)
            {
                if (tl1.val != tl2.val) return false;
                tl1 = tl1.next;
                tl2 = tl2.next;
            }
            if (tl1 == null && tl2 == null) return true;
            else return false;
        }

  }

# 地址

Q: https://leetcode.com/problems/add-two-numbers/

A: https://github.com/mofadeyunduo/LeetCode/tree/master/2AddTwoNumbers

(希望各位多多支持本人刚刚建立的GitHub和博客,谢谢,有问题可以邮件609092186@qq.com或者留言,我尽快回复)

LeetCode-2AddTwoNumbers(C#)的更多相关文章

  1. LeetCode in action

    (1) Linked List: 2-add-two-numbers,2.cpp 19-remove-nth-node-from-end-of-list,TBD 21-merge-two-sorted ...

  2. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  3. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  4. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  5. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  6. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  7. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  8. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  9. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  10. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

随机推荐

  1. 高性能Javascript--脚本的无阻塞加载策略

    Javascript在浏览器中的性能,可以说是前端开发者所要面对的最重要的可用性问题. 在Yahoo的Yslow23条规则当中,其中一条是将JS放在底部 .原因是,事实上,大多数浏览器使用单进程处理U ...

  2. C语言 · 时间转换

    问题描述 给定一个以秒为单位的时间t,要求用"<H>:<M>:<S>"的格式来表示这个时间.<H>表示时间,<M>表示分 ...

  3. CentOS7 重置root密码

    1- 在启动grub菜单,选择编辑选项启动 2 - 按键盘e键,来进入编辑界面 3 - 找到Linux 16的那一行,将ro改为rw init=/sysroot/bin/sh 4 - 现在按下 Con ...

  4. nodejs项目mysql使用sequelize支持存储emoji

    nodejs项目mysql使用sequelize支持存储emoji 本篇主要记录nodejs项目阿里云mysql如何支持存储emoji表情. 因由 最近项目遇到用户在文本输入emoji进行存储的时候导 ...

  5. Linux常用指令指南,终端装逼利器

    最近搞了台Macbook Pro,就学习了一下Linux命令,在网上查了些资料,看了本书叫<快乐的 Linux 命令行>,里面涉及到了各个方面的命令. 在此将常用的整理出来,以备将来使用. ...

  6. js面向对象学习 - 对象概念及创建对象

    原文地址:js面向对象学习笔记 一.对象概念 对象是什么?对象是“无序属性的集合,其属性可以包括基本值,对象或者函数”.也就是一组名值对的无序集合. 对象的特性(不可直接访问),也就是属性包含两种,数 ...

  7. golang语言构造函数

    1.构造函数定义 构造函数 ,是一种特殊的方法.主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中.特别的一个类可以有多个构造函数 ,可根据其参数个 ...

  8. Firebug中调试中的js脚本中中文内容显示为乱码

    Firebug中调试中的js脚本中中文内容显示为乱码 设置 页面 UFT-8 编码没用, 解决方法:点击 "Firebug"工具栏 中的"选项"---" ...

  9. osi(open system interconnection)模型的通俗理解

    OSI模型的理解: 以你和你女朋友以书信的方式进行通信为例. 1.物理层:运输工具,比如火车.汽车. 2.数据链路层:相当于货物核对单,表明里面有些什么东西,接受的时候确认一下是否正确(CRC检验). ...

  10. 零基础在线制作Windows Phone 8 应用

    任何用户(不管你是否会编程),只要你有浏览器,都可以使用 Windows Phone App Studio (下文中用App Studio指代) 快速制作出一个属于你的Windows Phone的应用 ...