34 · Bit Manipulation

#191 Number of 1 Bits

Easysolve on LeetCode ↗

frequently reported atAppleMicrosoftGoogleAmazon

the problem

In plain words

Given a positive integer n, return how many 1-bits are in its binary form (its Hamming weight). Older versions of the problem passed an unsigned 32-bit value, which arrives in Java as a possibly negative int, so make your code work for negatives too.

in n = 11

out 3

11 = 1011 in binary.

in n = 128

out 1

10000000.

in n = 2147483645

out 30

  • 1 ≤ n ≤ 2³¹ − 1 (current version)
  • Older versions allowed any 32-bit pattern, i.e. negative ints in Java

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #338
      Counting Bits
      Easyin Bits
    2. #231
      Power of Two
      Easyin Bits
    3. #190
      Reverse Bits
      Easyin Bits