码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode 338

时间:2016-06-02 06:17:37      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1‘s in their binary representation and return them as an array.

 

思路:数字总比[数字二进制最高位置0后的数字]的多一个1

 

public static int[] countBits(int num) {
        int len = num + 1;
        int[] res = new int[len];
        res[0] = 0;
        
        for (int i = 1; i < len; i++) {
            res[i] = res[Util.highBit(i)] + 1;
        }
        return res;
    }

//将二进制的最高位置0
    public static int highBit(int x) {
        return x - (int) Math.pow(2, (int) (Math.log(x) / Math.log(2)));
    }

 

leetCode 338

标签:

原文地址:http://www.cnblogs.com/zhaihua/p/5551684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!