leetcode刷题笔记--2. Add Two Numbers

原题链接 2. 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.

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

采取递归的方式实现

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    if l1 == nil {
        return l2
    }
    if l2 == nil {
        return l1
    }
    _sum := l1.Val + l2.Val
    res := &ListNode{Val:_sum % 10}
    res.Next = addTwoNumbers(l1.Next,l2.Next)
    if _sum >= 10 {
        res.Next = addTwoNumbers(res.Next,&ListNode{Val:1})
    }
    return res
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Cyber-dojo.org是编程操练者的乐园。下面是这个网站上的43个编程操练题目,供编程操练爱好者参考。 10...
    程序员吾真本阅读 5,869评论 1 2
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,147评论 0 13
  • 最近正在找实习,发现自己的算法实在是不能再渣渣,在网上查了一下,发现大家都在刷leetcode的题,于是乎本渣渣也...
    caoxian阅读 4,430评论 0 2
  • 我还是继续在上学期兼职的地方打工了。。。上学期想着再也不来这地方了,太累了!可是这学期因为要还花呗,而老爸就只给了...
    空木阅读 858评论 0 0
  • 保持沉默。就像一片废墟。没有风吹来。窗外。午后的阳光。焦灼。无处可逃。刚看完海子的故事,心里有些冷。“面朝大海,春...
    老资情调阅读 1,092评论 0 0