7.8

Algorithm

counting-bits

   class Solution {
    public  int[] countBits(int num) {
        List<Integer> numList = new ArrayList<Integer>();
        for (int i = 0; i <= num; i++) {
            numList.add(i);
        }
        int[] result = numList.parallelStream().mapToInt(number -> number = getBitNum(number)).toArray();
        return result;
    }

    private Integer getBitNum(Integer num) {
        int count = 0;
        while (num > 0) {
            int bit = num % 2;
            if (bit == 1) {
                count ++;
            }
            num/=2;
        }
        return count;
    }
}
/**
 *  数字   0    1   2   3   4   5   6   7   8
 *  二进   0    1  10  11  100 101 110 111 1000
 *  1个数  0   1   1   2   1   2   2   3   1
 *  
 *  当前数i如果能整除 count = (i/2的count)
 *  不能整除 count = (i/2的count + 1)
 */

public int[] countBits2(int num) {
    int[] ans = new int[num + 1];
    int i = 0;
    while (i <= num) {
        int d = i/2;
        int m = i%2;
        if (m == 0) {
            ans[i] = ans[d];
        }else {
            ans[i] = ans[d] + 1;
        }
        i++;
    }
    return ans;
}

Review

ThreadPoolExecutor 源码学习

Tip

用java8中的optional判空

 Optional.ofNullable(text).ifPresent(System.out::println);

Share

Java 8 中的 Streams API 详解