Top 150-InterviewEinfach

Anzahl der 1 Bits

Detaillierte Anleitung und Python-Implementierung für das Problem „Anzahl 1 Bits“.

Problemstellung

Einfach

Schreiben Sie eine Funktion, die die binäre Darstellung einer positiven ganzen Zahl annimmt und die Anzahl der gesetzten Bits zurückgibt (auch als Hamming-Gewicht bezeichnet).

Schreiben Sie eine Funktion hammingWeight(n: int) -> int.

Einschränkungen
  • n must be a positive integer up to 2^32 - 1

Beispiele

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?
Erwägen Sie die Verwendung von Bitmanipulations-spezifischen Datenstrukturen wie Sets oder Heaps.
Edge Cases to Watch
  • Leere Eingabestrukturen
  • Einzelelementeingaben
  • Große numerische Grenzen

Bereit zur Lösung?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Im Editor öffnen
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

Empfohlene Python-Ressourcen

Erweitern Sie Ihr Wissen mit zugehörigen interaktiven Tutorials, Spickzetteln und Codevergleichen.