Count number of 1's in binary representation

后端 未结 21 2044
天涯浪人
天涯浪人 2020-11-28 01:32

Efficient way to count number of 1s in the binary representation of a number in O(1) if you have enough memory to play with. This is an interview question I found on an onli

21条回答
  •  再見小時候
    2020-11-28 01:56

    The following is a C solution using bit operators:

    int numberOfOneBitsInInteger(int input) {
      int numOneBits = 0;
    
      int currNum = input;
      while (currNum != 0) {
        if ((currNum & 1) == 1) {
          numOneBits++;
        }
        currNum = currNum >> 1;
      }
      return numOneBits;
    }
    

    The following is a Java solution using powers of 2:

    public static int numOnesInBinary(int n) {
    
      if (n < 0) return -1;
    
      int j = 0;
      while ( n > Math.pow(2, j)) j++;
    
      int result = 0;
      for (int i=j; i >=0; i--){
        if (n >= Math.pow(2, i)) {
            n = (int) (n - Math.pow(2,i));
            result++;    
        }
      }
    
      return result;
    }
    

提交回复
热议问题