Count number of 1's in binary representation

后端 未结 21 2024
天涯浪人
天涯浪人 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 02:00

    public static void main(String[] args) {
    
        int a = 3;
        int orig = a;
        int count = 0;
        while(a>0)
        {
            a = a >> 1 << 1;
            if(orig-a==1)
                count++;
            orig = a >> 1;
            a = orig;
        }
    
        System.out.println("Number of 1s are: "+count);
    }
    

提交回复
热议问题