Le migliori 150 intervisteFacile

Aggiungi due numeri

Guida dettagliata e implementazione Python per il problema "Aggiungi due numeri".

Dichiarazione del problema

Facile

Ti vengono fornite due liste collegate non vuote che rappresentano due numeri interi non negativi. Le cifre vengono memorizzate in ordine inverso e ciascuno dei relativi nodi contiene una singola cifra. Aggiungi i due numeri e restituisci la somma come elenco collegato.

Puoi supporre che i due numeri non contengano nessuno zero iniziale, tranne il numero 0 stesso.

Gli elenchi collegati sono rappresentati come elenchi Python. Implementa una funzione addTwoNumbers(l1: list, l2: list) -> list che restituisce la somma come elenco in ordine di cifre inverso.

Vincoli
  • The number of nodes in each linked list is in the range [1, 100]
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros

Esempi

Example 1
Input
[2,4,3], [5,6,4]
Output
[7,0,8]
Explanation

342 + 465 = 807. Represented in reverse: [7,0,8].

Example 2
Input
[0], [0]
Output
[0]
Explanation

0 + 0 = 0.

Example 3
Input
[9,9,9,9,9,9,9], [9,9,9,9]
Output
[8,9,9,9,0,0,0,1]
Explanation

9999999 + 9999 = 10009998. Represented in reverse: [8,9,9,9,0,0,0,1].

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche dell'elenco collegato come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.