Le migliori 150 intervisteFacile

Conteggio dei bit

Guida dettagliata e implementazione Python per il problema del "conteggio dei bit".

Dichiarazione del problema

Facile

Dato un intero n, restituire un array ans di lunghezza n + 1 tale che per ogni i (0 <= i <= n), ans[i] è il numero di 1 nella rappresentazione binaria di i.

Scrivi una funzione countBits(n: int) -> List[int].

Vincoli
  • 0 <= n <= 10^5

Esempi

Example 1
Input
n = 2
Output
[0,1,1]
Explanation

0 -> 0; 1 -> 1; 2 -> 10.

Example 2
Input
n = 5
Output
[0,1,1,2,1,2]
Explanation

0 -> 0; 1 -> 1; 2 -> 1; 3 -> 2; 4 -> 1; 5 -> 2.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche per la manipolazione dei bit 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.