您的位置:首页 > 其它

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++:

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;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: