Count number of 1's in binary representation

后端 未结 21 2075
天涯浪人
天涯浪人 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条回答
  •  旧时难觅i
    2020-11-28 02:15

    The function takes an int and returns the number of Ones in binary representation

    public static int findOnes(int number)
    {
    
       if(number < 2)
        {
            if(number == 1)
            {
                count ++;
            }
            else
            {
                return 0;
            }
        }
    
        value = number % 2;
    
        if(number != 1 && value == 1)
            count ++;
    
        number /= 2;
    
        findOnes(number);
    
        return count;
    }
    

提交回复
热议问题