LeetCode002__Add Two Numbers
2016-08-07 21:28
399 查看
照常题目先放上来:
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
没啥想法,强力破解呗~
代码如下:
结果,恩不错~然后提交……
问题来了:
WTF!!!不能忍,没说一位数要变成两位呀,坑!
改吧……
分情况了:有进位,无进位,两个数位数不相同……
讨论多种情况再来:
提交,搞定收工!
结果图:
为什么java和c++可以那么快?等我刷完python要不要用java重写一把呢?
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
没啥想法,强力破解呗~
代码如下:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ solution = ListNode(0) p=solution flag=0 while l2 and l1: p.next=ListNode((l2.val+l1.val+flag)%10) if l2.val+l1.val+flag>=10: flag=1 p.next.var=1 else: flag=0 l2=l2.next l1=l1.next p=p.next return solution.next
结果,恩不错~然后提交……
问题来了:
WTF!!!不能忍,没说一位数要变成两位呀,坑!
改吧……
分情况了:有进位,无进位,两个数位数不相同……
讨论多种情况再来:
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ solution = ListNode(0) p=solution flag=0 while l2 and l1: p.next=ListNode((l2.val+l1.val+flag)%10) if l2.val+l1.val+flag>=10: flag=1 p.next.next=ListNode(1) print flag,p.next.val else: flag=0 #p.next.next=ListNode(0) l2=l2.next l1=l1.next p=p.next while l1: p.next=ListNode((flag+l1.val)%10) if l1.val+flag>=10: flag=1 p.next.next=ListNode(1) else: flag=0 l1=l1.next p=p.next while l2: p.next=ListNode((flag+l2.val)%10) if l2.val+flag>=10: flag=1 p.next.next=ListNode(1) else: flag=0 l2=l2.next p=p.next return solution.next
提交,搞定收工!
结果图:
为什么java和c++可以那么快?等我刷完python要不要用java重写一把呢?
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】
- LeetCode 002, Add Two Numbers
- LeetCode-Add Two Numbers_002
- [LeetCode]-002-Add Two Numbers
- LeetCode 002 AddTwoNumbers
- leetcode 002 Add_Two_Numbers
- leetcode 002 Add Two Numbers
- 2017-09-07 LeetCode_002 Add Two Numbers
- leetcode002 Add Two Numbers
- 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】
- LeetCode 002 Add Two Numbers
- 【LeetCode002-003算法/编程练习C++】---Add Two Numbers||寻找最长无重复字母子串。//第三题之后有空要再想一想…
- [LeetCode]题解(python):002-Add Two Numbers
- LeetCode 002 Add Two Numbers
- leetcode 002 Add Two Numbers(java)
- LeetCode 002-Add Two Numbers
- LeetCode002 Add Two Numbers
- 【leetcode】002 Add Two Numbers
- LeetCode 002 AddTwoNumbers
- leetcode解题方案--002--AddTwoNumbers