Python Nozioni di baseFacile

N bit binary numbers

Guida dettagliata e implementazione Python per il problema dei "numeri binari a N bit".

Dichiarazione del problema

Facile

Scrivi una funzione n_bit_binary(n) che generi tutti i numeri binari a n bit (come stringhe) in modo tale che in ogni prefisso della stringa binaria, il numero di 1 sia maggiore o uguale al numero di 0. Restituisce il risultato come un elenco ordinato di stringhe in ordine lessicografico.

Vincoli
  • 1 <= n <= 15

Esempi

Example 1
Input
n = 3
Output
['110', '111']
Explanation

For '110': prefixes '1'(1>=0✓), '11'(2>=0✓), '110'(2>=1✓). For '111': all prefixes have more 1s. '100','101','010' etc. fail the prefix condition.

Example 2
Input
n = 2
Output
['10', '11']
Explanation

'10': prefix '1' has 1>=0✓, '10' has 1>=1✓. '11': both prefixes valid. '00','01' fail.

Example 3
Input
n = 1
Output
['1']
Explanation

Only '1' satisfies the condition. '0' has prefix '0' with 0 ones and 1 zero.

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