2_Add Two Numbers
来源:互联网 发布:女包包网淘宝网 编辑:程序博客网 时间:2024/06/11 23:27
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.
你可以假设这两个数值不是以0开头,也就是假设这两个数值是正常合法的
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
我的解:
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ p = 0 result = None current = None while True: addValue = l1.val + l2.val + p p = 0 if addValue >= 10: addValue = addValue - 10 p = 1 node = ListNode(addValue) if result == None: result = node current = node else: current.next = node current = node l1 = l1.next l2 = l2.next if l1 == None or l2 == None: break if l1 == None and l2 == None: pass elif l1 == None or l2 == None: rest = None if l1 == None: rest = l2 else : rest = l1 while True: addValue = p + rest.val p = 0 if addValue >= 10: addValue = addValue - 10 p = 1 node = ListNode(addValue) current.next = node current = node rest = rest.next if rest == None: break if p == 0: return result else: node = ListNode(p) current.next = node return result
看了答案才知道可以更简洁一些的 ~_~
阅读全文
0 0
- 2_Add Two Numbers
- leetcode(2)_Add Two Numbers
- LeetCode 2_Add Two Numbers
- LeetCode 2_Add Two Numbers
- 【LeetCode】2_Add Two Numbers
- LeetCode之2_Add Two Numbers
- 0002_Add Two Numbers
- 2_Add Two Number
- leetcode第一刷_Add Two Numbers
- Leetcode第二题_Add Two Numbers
- 2 Add Two Numbers
- 2、Add Two Numbers
- 2、Add Two Numbers
- 2 Add Two Numbers
- 2Add Two Numbers
- #2 Add Two Numbers
- 2 - Add Two Numbers
- 2Add Two Numbers
- linux学习总结 unit06进程管理
- 原型模式
- java自定义Exception
- Android零基础入门第14节:使用高速Genymotion,跨入火箭时代
- How Many Tables
- 2_Add Two Numbers
- 表单提交设置disabled属性的input数据未提交
- 【Node.js-1】NodeJS简单入门、http、fs、url、querystring、接收客户端get/post数据
- HDU 1465 不容易系列之一(错排公式推导)
- 设置背景透明度
- hdu 1074 状态压缩DP 贪心错的原因(D)
- c++笔记
- NOIP2017测试(7.24)
- 这一刻让我明白大师为什么如此令人尊敬