Python Nozioni di baseFacile

Conversione da binario a decimale

Guida dettagliata e implementazione Python per il problema della "conversione da binario a decimale".

Dichiarazione del problema

Facile

Scrivi una funzione binary_to_decimal(binary_str) che accetta una stringa che rappresenta un numero binario (contenente solo '0' e '1') e restituisce il suo equivalente intero decimale (base 10).

Ogni cifra in un numero binario rappresenta una potenza di 2, a partire dalla cifra più a destra (2^0). Ad esempio, binario '1010' = 1×2³ + 0×2² + 1×2¹ + 0×2⁰ = 8 + 0 + 2 + 0 = 10.

Vincoli
  • 1 <= len(binary_str) <= 20
  • binary_str contains only '0' and '1'

Esempi

Example 1
Input
binary_to_decimal('1010')
Output
10
Explanation

1×2³ + 0×2² + 1×2¹ + 0×2⁰ = 8 + 0 + 2 + 0 = 10.

Example 2
Input
binary_to_decimal('1111')
Output
15
Explanation

1×2³ + 1×2² + 1×2¹ + 1×2⁰ = 8 + 4 + 2 + 1 = 15.

Example 3
Input
binary_to_decimal('10000')
Output
16
Explanation

1×2⁴ = 16.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Numbers 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.