Count Set Bits

Problem

Read a non-negative integer n (n < 2^31) and print how many 1 bits it has in binary.

Constraints

  • 0 <= n < 2^31

Examples

Input

13

Output

3

Solutions

Better approachTime O(log n)Space O(1)

We look at the last bit, add it, and shift. We repeat until the number is 0.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count the 1 bits of a number.
 * Input   : One integer n >= 0.
 * Output  : The number of set bits.
 * Approach: Check bit by bit.
 * Time    : O(log n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(long n) {
        // Step 1: The count starts at 0.
        int count = 0;

        // Step 2: Repeat while the number has bits left.
        while (n > 0) {
            // Step 3: n & 1 is the last bit (0 or 1). Add it to the count.
            count += (int) (n & 1);

            // Step 4: Shift right by 1 to drop the last bit.
            n = n >> 1;
        }
        return count;
    }

    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        System.out.println(solve(n));
    }
}
Hints (1)
  1. Which operator gives the last bit?