Le migliori 150 intervisteFacile

Numero di 1 bit

Guida dettagliata e implementazione Python per il problema "Numero di 1 bit".

Dichiarazione del problema

Facile

Scrivere una funzione che prenda la rappresentazione binaria di un intero positivo e restituisca il numero di bit impostati che ha (noto anche come peso di Hamming).

Scrivi una funzione hammingWeight(n: int) -> int.

Vincoli
  • n must be a positive integer up to 2^32 - 1

Esempi

Example 1
Input
n = 11
Output
3
Explanation

The binary representation of 11 is 1011, which has 3 set bits.

Example 2
Input
n = 128
Output
1
Explanation

The binary representation of 128 is 10000000, which has 1 set bit.

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.