我知道 StackOverflow 不会编写问题并获取答案站点,但这是我在 leetcode 中遇到的问题。
l1 = input()
l2 = input()
def f(x): #Gives reversed of linkedlist ex. [2, 4, 3] return 342
a, u = 0, 0
for ele in x:
if ele.isnumeric():
a += int(ele)*(10**u)
u += 1
return a
l = list(int(i) for i in str(f(l1) + f(l2)))
print(list(reversed(l)))
这个问题是leet code problem所以在这里我已经解决了问题,但这是不同的,他们不希望逗号后的数字之间有空格。
输入:[2,4,3] [5,6,4]
我的输出: [7,0,8]
预期输出:[7,0,8]
不过,我也尝试过
k = str(f(l1) + f(l2))
print("[" + ",".join(str(k)[::-1]) + "]")
最佳答案
你不应该在leetcode上使用input()和print()
当你开始解决问题时,他们会给你一个函数,你必须填写并返回结果。
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
#put your code here
return the_result
这个问题应该使用一个链表,其节点定义为
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
这应该是您应该编码的 addTwoNumbers()
方法的输入。
但不知何故,通过使用 input()
你可以绕过这个并获取原始列表。
此外,prints(stdout) 并不是 leetcode 系统正在评估的内容,它们会查找 addTwoNumbers()
的输出,在本例中为空白。
关于python - 链表和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70225519/