温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetCode 338. Counting Bits | Dynamic Programming | Medium

发布时间:2020-07-19 04:16:00 来源:网络 阅读:487 作者:313119992 栏目:开发技术

338. Counting Bits


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.

Example:
For num = 5 you should return [0,1,1,2,1,2].

题目大意:

给一个数字,比如5,那么5之前所有的整数的每个二进制表示中1的个数。

思路:

数字二进制表示二进制中1的个数
000
1
11
2
101
3112
41001
51012
61102
71113
810001
910012
1010102
1110113
1211002
1311013
1411103
1511114
16100001
根据上面分析的到一个规律:每达到2的i次方,就会从第一个元素开始依次加1,赋值给当前元素到下一次达到2的i+1次方的元素。


代码如下:

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result;
        if(num == 0)
        {
            result.push_back(0);
            return result;
        }
        if(num == 1)
        {
            result.push_back(0);
            result.push_back(1);
            return result;
        }
        result.push_back(0);
        result.push_back(1);
        
        int temp = 2;
        for(int i = 2; i <=num ; i++)
        {
            if(i == temp*2)
                temp *= 2;
            result.push_back(result[i-temp] + 1);
        }
        return result;
    }
};


2016-09-01 18:57:26

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI