# Python练习：解题 - 两数相加（JS, TS, PY3版）

Python练习：解题 - 两数相加（JS, TS, PY3版）
JS版

/**

• @param {ListNode} l1
• @param {ListNode} l2
• @return {ListNode}
*/const addTwoNumbers = (l1, l2) => {

let l3 = null
let cache = 0
let tens = 0
while (l1 || l2) {
let total = 0
if (l1) {
l1 = l1.next }
if (l2) {
l2 = l2.next }
total += tens if (total >= 10) {
total -= 10
tens = 1
} else {
tens = 0
}
let node = new ListNode(total)
if (cache) {
cache.next = node
cache = node } else {
l3 = node
cache = l3 }
}
if (tens === 1) {
cache.next = new ListNode(1)
}
return l3}

TS版

class ListNode {
val: number
next: ListNode | any
constructor(value: number) {
this.val = value this.next = null
}}
/**

• @param {ListNode} l1
• @param {ListNode} l2
• @return {ListNode}
*/const addTwoNumbers = (l1: ListNode, l2: ListNode) => {

let l3: null | ListNode = null
let cache: ListNode | null = null
let tens: number = 0
while (l1 || l2) {
let total: number = 0
if (l1) {
l1 = l1.next }
if (l2) {
l2 = l2.next }
total += tens if (total >= 10) {
total -= 10
tens = 1
} else {
tens = 0
}
let node = new ListNode(total)
if (cache) {
cache.next = node
cache = node } else {
l3 = node
cache = l3 }
}
if (tens === 1) {
cache.next = new ListNode(1)
}
return l3}
PY版

# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:

def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = None
cache = 0
tens = 0
while l1 or l2:
total = 0
if l1:
l1 = l1.next
if l2:
l2 = l2.next
total = total + tens if total >= 10:
total = total - 10
tens = 1
else:
tens = 0
node = ListNode(total)
if cache:
cache.next = node
cache = node else:
l3 = node
cache = l3 if tens == 1:
cache.next = ListNode(1)
return l3

|
13天前
|
Web App开发 JavaScript 前端开发

19 1
|
1月前
|

71 1
|
29天前
|
JavaScript 算法 前端开发

153 1
|
12天前
|
Web App开发 JavaScript 前端开发

【8月更文挑战第29天】在数字化时代，掌握一门后端编程语言变得尤为重要。Node.js作为一种基于JavaScript的服务端平台，因其高性能、轻量级的特性而广受欢迎。本文将引导读者了解Node.js的基本概念、核心模块以及如何利用它来构建一个简易的Web服务器。通过本文的学习，你将获得使用Node.js进行后端开发的初步技能，并理解其在现代Web开发中的应用价值。
8 0
|
2月前
|

40 2
|
2月前
|
Python
Python推导式：小练习
Python推导式：小练习
21 2
|
2月前
|
Python
Python 练习实例35
Python 练习实例35
79 2
|
2月前
|
Python
Python 练习实例34
Python 练习实例34
25 2
|
2月前
|
Python
Python 练习实例36
Python 练习实例36
18 1
|
3月前
|
Python
Python 练习实例33
Python 练习实例33
29 2

DDNS