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
我想弱弱的问问就我一个人念不懂题目吗?不是英语水平的问题,这题目的表述我真是无法理解,给个例子我也很懵逼的,这个8我想了半天,又看答案,都没明白,后来恍然明白,是进位,逢10进位至下一位,或者说是(右?)移位吧,你们能从题目里面读出这个隐含意思来吗,例子也不多给几个数
我最近执迷于用Python,因为我没学过C++,然而,我的数据结构学的是严奶奶版本的,还是看c++舒服,我这都学的什么乱七八糟的啊,自从考完研就没再看过算法了
这个答案是人家的高分答案,要不然我连题目都还看不懂呢
# Definition for singly-linked list.
# class ListNode(object): #这个不写typedef struct 直接就写class啊
# 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
"""
c=0#初始化进位
root=r=ListNode(0)
while l1 or l2 or c:
val1=0
val2=0 #我觉得不用这俩
if l1:
val1=l1.val
next1=l1.next
if l2:
val2=l2.val
next2=l2.next
s=val1+val2+c
c,s=divmod(s,10)#返回商(往右进位的value,下个节点val直接加),余数(当前节点的value)
root.next=ListNode(s)#直接申请节点,这我都忘了,我这两年是去吃屎了吗,不不不是学掉包了
r=root.next#更新尾指针
return root.next #我在想为啥要.next???
C++:
struct ListNode{
int val;
ListNode *next
ListNode(int x):val(x),next(NULL){}
}
class Solution{
public:
ListNode *addTwoNumbers(ListNode*l1,ListNode* l2):{
ListNode res(0)
*r=&res #尾指针
int c=0; int s=0;
while(l1||l2||c):
s=l1->val+l2->val+c
c=int(s/10)
s=int(s%10)
res->next=new ListNode(s)
r=res->next
l1=l1->next
l2=l2->next }
return res.next
}