LeetCode (Add Two Numbers)
2017-03-25 19:58
441 查看
Problem:
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
C++:
Python:
# 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
"""
tmp = ans = ListNode(0);
cin = 0;
while(l1 or l2 or cin):
val1 = l1.val if(l1) else 0;
val2 = l2.val if(l2) else 0;
val = (val1 + val2 + cin) % 10;
cin = (val1 + val2 + cin) // 10;
tmp.next = ListNode(val);
l1 = l1.next if(l1) else l1;
l2 = l2.next if(l2) else l2;
tmp = tmp.next;
return ans.next;
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
C++:
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode l(0),*p=&l; int s = 0; while (l1 || l2 || s){ int i = l1?l1->val:0; int j = l2?l2->val:0; int k = (i+j+s)%10; p->next=new ListNode(k); s = (i+j+s)/10; l1=l1?l1->next:0; l2=l2?l2->next:0; p = p->next; } return l.next; } };
Python:
# 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
"""
tmp = ans = ListNode(0);
cin = 0;
while(l1 or l2 or cin):
val1 = l1.val if(l1) else 0;
val2 = l2.val if(l2) else 0;
val = (val1 + val2 + cin) % 10;
cin = (val1 + val2 + cin) // 10;
tmp.next = ListNode(val);
l1 = l1.next if(l1) else l1;
l2 = l2.next if(l2) else l2;
tmp = tmp.next;
return ans.next;
相关文章推荐
- Leetcode Add Two Numbers
- Leetcode:Add Two Numbers
- [leetcode][list] Add Two Numbers
- leetCode刷题记录-2. Add Two Numbers
- LeetCode | 2. Add Two Numbers
- #2 LeetCode——Add Two Numbers
- leetcode 2. Add Two Numbers
- LeetCode: Add Two Numbers
- LeetCode:Add Two Numbers
- LeetCode-Add Two Numbers
- LeetCode Add Two Numbers
- LeetCode-Add Two Numbers-Java
- leetcode 2 Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters
- LeetCode Add Two Numbers
- 【LeetCode】2. Add Two Numbers 解题报告
- LeetCode: 2. Add Two Numbers 【C 解题】
- LeetCode 2. Add Two Numbers(C++)
- LeetCode2:Add Two Numbers