Count 1 in Binary

Question

  1. Count how many 1 in binary representation of a 32-bit integer.
  2. Example
  3. Given 32, return 1
  4. Given 5, return 2
  5. Given 1023, return 9
  6. Challenge
  7. If the integer is n bits with m 1 bits. Can you do it in O(m) time?

题解

O1 Check Power of 2 的进阶版,x & (x - 1) 的含义为去掉二进制数中1的最后一位,无论 x 是正数还是负数都成立。

C++

  1. class Solution {
  2. public:
  3. /**
  4. * @param num: an integer
  5. * @return: an integer, the number of ones in num
  6. */
  7. int countOnes(int num) {
  8. int count=0;
  9. while (num) {
  10. num &= num-1;
  11. count++;
  12. }
  13. return count;
  14. }
  15. };

Java

  1. public class Solution {
  2. /**
  3. * @param num: an integer
  4. * @return: an integer, the number of ones in num
  5. */
  6. public int countOnes(int num) {
  7. int count = 0;
  8. while (num != 0) {
  9. num = num & (num - 1);
  10. count++;
  11. }
  12. return count;
  13. }
  14. }

源码分析

累加计数器即可。

复杂度分析

这种算法依赖于数中1的个数,时间复杂度为 O(m). 空间复杂度 O(1).

Reference