Start learning free

LESSON 588 OF 671 · BIT MANIPULATION

Number of 1 Bits in Java: Clearing the Lowest Set Bit

Practice O(k) Read the full explanation

Given a non-negative integer n, return the number of 1 bits in its binary representation (also called its Hamming weight).

 

Example 1:

Input: n = 11
Output: 3
Explanation: 11 in binary is 1011, which has three 1 bits.

Example 2:

Input: n = 128
Output: 1
Explanation: 128 in binary is 10000000, which has a single 1 bit.

Example 3:

Input: n = 2147483645
Output: 30
Explanation: 2147483645 in binary is 1111111111111111111111111111101: thirty-one digits, and all but one of them are 1.

 

Constraints:

  • 0 <= n <= 231 - 1
Note:

Your algorithm should run in O(k) time, where k is the number of 1 bits in n, and use O(1) extra space.



Look at what subtracting 1 does to a number in binary: its lowest 1 bit turns into 0, every 0 below it turns into 1, and the higher bits stay the same. For example, 12 is 1100 and 11 is 1011.

So n AND n - 1 is n with its lowest 1 bit removed: 1100 AND 1011 is 1000. Keep doing it until n becomes 0, and count how many times you did it.

Each pass of the loop removes one 1 bit, so the loop runs k times, at most 31 for these values: O(k) time.
We keep only the count and the number we change, so the extra space is O(1).
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · BIT MANIPULATION

    Number Of 1 Bits in Java, explained

    Problem overview

    The method hammingWeight(int n) receives a non-negative integer and returns how many 1 bits its binary form has. For n = 11, which is 1011 in binary, the answer is 3. For n = 128, which is 10000000, the answer is 1. For n = 2147483645, which is 31 binary digits with a single 0, the answer is 30.

    The target is O(k) time, where k is the number of 1 bits, and O(1) extra space.

    Approach: remove one 1 bit per pass

    The obvious way tests all 31 or 32 bit positions one by one: check the last bit with n & 1, shift right, repeat. It works, but it always takes as many passes as there are bit positions, even for a number like 128 that has a single 1.

    This lesson uses a trick that does one pass per 1 bit. The expression n & (n - 1) clears the lowest 1 bit of n. Subtracting 1 turns that lowest 1 into a 0 and turns all the 0s below it into 1s. Bits above it are unchanged. AND-ing the result with n keeps only the bits that are 1 in both, which are exactly the bits above the lowest 1.

    For example, 12 is 1100 and 11 is 1011, and 12 & 11 is 1000, which is 8: 12 without its lowest 1 bit. Repeating the operation removes one 1 bit each time, so n reaches 0 after exactly as many passes as it had 1 bits. Counting the passes gives the answer.

    For n = 11 the loop goes through these values:

    n=10 (1010) count=1
    n=8 (1000) count=2
    n=0 (0) count=3
    

    Step by step

    1. Create count as an int starting at 0. It counts the 1 bits as they are removed.
    2. Loop while n != 0. Each pass removes one 1 bit, so n becomes 0 right after its last 1 bit is gone.
    3. Clear the lowest 1 bit: n = n & (n - 1).
    4. Add 1 to count, because one more 1 bit has been removed.
    5. Return count.

    The solution in Java

    class Solution {
        public int hammingWeight(int n) {
            int count = 0;
            while (n != 0) {
                n = n & (n - 1);
                count++;
            }
            return count;
        }
    }
    

    The Java details worth a closer look:

    • Operator precedence. In Java, - binds tighter than &, so n & n - 1 would mean the same thing. The parentheses are there for the reader.
    • The parameter is a copy. Assigning to n changes only the method's own copy, so the caller's number is untouched.
    • n - 1 never overflows here. The loop only subtracts when n != 0 and the lesson's values are non-negative, so n - 1 is at least 0.
    • Negative numbers also terminate. An int is 32 bits and negative numbers keep their sign bit as a 1. The same loop gives 32 for -1, because every one of the 32 bits is a 1. The trick still removes one 1 bit per pass, so it ends after at most 32 passes.

    Complexity

    Time: O(k), where k is the number of 1 bits. Each pass removes one of them, and an int has at most 32 bits, so the loop runs at most 32 times.

    Space: O(1). Only count and the parameter n are used.

    Edge cases and common mistakes

    • Zero. The loop never runs and the method returns 0.
    • A power of two. 128 & 127 is 0, so the loop runs once and returns 1.
    • The largest value. 2147483647 has 31 bits set, so the loop runs 31 times and returns 31.
    • Looping n > 0. For the lesson's non-negative values it behaves the same as n != 0, but it would stop immediately for a negative number and return 0.
    • Forgetting to update n. Writing n & (n - 1) without assigning the result changes nothing, and the loop never ends.
    • Using >> on a negative number. A right shift with >> copies the sign bit, so a loop like while (n != 0) { count += n & 1; n >>= 1; } never ends for a negative n. >>> fills with zeros instead.

    Testing

    • n = 0 gives 0.
    • n = 11 gives 3.
    • n = 12 gives 2.
    • n = 128 gives 1.
    • n = 2147483645 gives 30.
    • n = 2147483647 gives 31.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free