Count 1's in binary representation in O(n) and O(log n) where n is number of bits

Michu93 :

I have two task - count 1's in binary representation in O(n) and O(log n). As the first part is easy, I can't figure out how can I count them in O(log n) as it's not sorted or anything. Is that even possible? My code so far:

public class CountOnes {
  public static void main(String[] args)
  {
    System.out.println("Program to count ones");
    countOnesInLinearTime("110");
    countOnesInlogarithmicTime("110");
  }

  private static void countOnesInlogarithmicTime(String binaryRepresentationOfLong) {
    //TODO
  }

  private static void countOnesInLinearTime(String binaryRepresentationOfLong) {
    int numberOfOnes = 0;
    for(int i = 0; i < binaryRepresentationOfLong.length(); i++)
    {
      if(binaryRepresentationOfLong.charAt(i) == '1')
      {
        numberOfOnes++;
      }
    }
    System.out.println(numberOfOnes);
  }
}

I have found: Count number of 1's in binary representation but it's slightly different.

Kaidul :

Assuming your input string will be integer, not in string, it's achievable using Brian Kernighan’s Algorithm:

Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the rightmost set bit). So if we subtract a number by 1 and do bitwise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count.

The beauty of this solution is the number of times it loops is equal to the number of set bits in a given integer.

1. Initialize count: = 0
2. If integer n is not zero
      (a) Do bitwise & with (n-1) and assign the value back to n
          n: = n&(n-1)
      (b) Increment count by 1
      (c) go to step 2
3. Else return count

Implementation

int countNumberOfOnes(int n) { 
    int count = 0; 
    while (n > 0) { 
        n &= (n - 1); 
        count++; 
    } 
    return count; 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115453&siteId=1