Python Nozioni di baseFacile

Conversione da decimale a binario

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

Dichiarazione del problema

Facile

Scrivi una funzione decimal_to_binary(n) che accetta un intero non negativo n e restituisce una stringa che rappresenta il suo equivalente binario (base 2). Non includere zeri iniziali (ad eccezione dell'input 0, che dovrebbe restituire "0").

Per convertire il numero decimale in binario, dividi ripetutamente il numero per 2 e raccogli i resti in ordine inverso.

Vincoli
  • 0 <= n <= 10^6

Esempi

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

10 ÷ 2 = 5 remainder 0, 5 ÷ 2 = 2 remainder 1, 2 ÷ 2 = 1 remainder 0, 1 ÷ 2 = 0 remainder 1. Reading remainders bottom-up: 1010.

Example 2
Input
decimal_to_binary(255)
Output
'11111111'
Explanation

255 in binary is eight 1s: 128+64+32+16+8+4+2+1 = 255.

Example 3
Input
decimal_to_binary(0)
Output
'0'
Explanation

0 in any base is 0.

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.