与运算

2016-11-13  本文已影响0人  syimo

与运算

问题:

高效运算.PNG

/**
 * 取一个数字二进制的最后一位,则&1;如果要取4位,则&15;即(2的N次-1)
 * 例如把9表示成二进制是1001 ,有2位是1. 因此如果输入9,该出2。
 * >>>代表无符号右移,最高位补为0。>>有符号的右移,最高位补上原来的最高位
 * 
 * @author xhq
 *
 */
public class N10 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(function1(9));
        System.out.println(function2(9));
    }

    public static int function1(int n) {
        // int型,在java中占32个字节,运行32次。这样包括负数。
        // 每次运算,将末尾的一个数字移除
        int result = 0;
        for (int i = 0; i < 32; i++) {
            if ((n & 1) == 1)
                result++;
            n = n >>> 1;
        }
        return result;
    }

    public static int function2(int n) {
        
        //把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0。
        //那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作
        int result = 0;
        while (n > 0) {
            result++;
            n = n & (n - 1);
        }
        return result;
    }

}

参考

二进制中1的个数

上一篇下一篇

猜你喜欢

热点阅读