Python Nozioni di baseFacile

Conversione da binario a ottale

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

Dichiarazione del problema

Facile

Scrivi una funzione binary_to_octal(binary_str) che accetta una stringa che rappresenta un numero binario e restituisce una stringa che rappresenta il suo equivalente ottale (base 8). Non includere zeri iniziali nell'output (ad eccezione dell'input '0').

Suggerimento: raggruppa le cifre binarie in gruppi di 3 da destra a sinistra, quindi converti ciascun gruppo nella sua cifra ottale.

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

Esempi

Example 1
Input
binary_to_octal('1010')
Output
'12'
Explanation

Group from right: 001 010. 001 = 1, 010 = 2. So octal is 12. (Binary 1010 = Decimal 10 = Octal 12.)

Example 2
Input
binary_to_octal('111111')
Output
'77'
Explanation

Group: 111 111. 111 = 7, 111 = 7. Octal is 77. (Binary 111111 = Decimal 63 = Octal 77.)

Example 3
Input
binary_to_octal('11001010')
Output
'312'
Explanation

Group from right: 011 001 010. 011=3, 001=1, 010=2. Octal is 312. (Binary 11001010 = Decimal 202 = Octal 312.)

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.