Java, a binary integer number of 1s

This is a company face questions this year:

General idea is: to convert into a binary integer n character array, and a number of a:

private static int helper1(int i) {
    char[] chs = Integer.toBinaryString(i).toCharArray();
    int res = 0;
    for (int j = 0; j < chs.length; j++) {
        if (chs[j] == '1') {
            res++;
        }
    }
    return res;
}

 

The second method is: the integer n 1 and an AND operation , the least significant bit when the integer n is 1, the result is 1, 0 otherwise. Then the left one 1 , proceed with the operation and n, when the low times is 1, the result is nonzero, otherwise the result is 0. Operation cycles or more, the number of non-zero can be recorded. 

    public static int helper2(int n ){

        int count = 0;
        int flag = 1;
        while(flag <= n){
            if((n&flag) != 0)
                count++;
            flag = flag<<1;
        }
        return count;
    }

 

A third method is: the integer n 1 and an AND operation , the least significant bit when the integer n is 1, the result is 1, 0 otherwise. Then the n right one , continue with the operation and 1. Cyclic operation above, n = 0 until the end of the recording nonzero (1) to the number.

    private static int helper3(int n) {
        int res = 0;
        while (n!=0) {
            if ((n&1) == 1) {
                res++;
            }
            n = n>>1;
        }
        return res;
    }

 

The fourth method is: the integer n and the (n-1) with the calculation : the integer is decremented by 1, and then do with the original integer arithmetic, which will become an integer of 0 rightmost. Then the binary representation of an integer in the number of 1, on how many times such an operation can be performed. Thus the number of comparisons can be reduced.

    private static int helper4(int n) {
        int res = 0;
        while (n!=0) {
            res++;
            n = n&(n-1);
        }
        return res;
    }

 

 

Over...

 

reference:

1. the Java seeking a binary integer number of 1s

 

Guess you like

Origin www.cnblogs.com/gjmhome/p/11423301.html