public class Solution {
public int[] CountBits(int num) {
var ary = new int[num + ]; for (int i = ; i <= num; i++)
{
var count = ;
var cur = i;
do
{
var c = cur % ;
if (c == )
{
count++;
}
cur = cur / ;
} while (cur != ); ary[i] = count;
} return ary;
}
}

https://leetcode.com/problems/counting-bits/#/description

另一个版本,246ms:

public class Solution
{
public int[] CountBits(int num)
{
int[] counts = new int[num + ];
for (int i = ; i <= num; i++)
{
int n = i;
int count = ;
while (n != )
{
if ((n & ) == )
{
count++;
}
n >>= ;
}
counts[i] = count;
}
return counts;
}
}

补充一个使用动态规划思想的代码,使用python实现:

 class Solution:
def countBits(self, num: 'int') -> 'List[int]':
if num==0:
return [0]
elif num==1:
return [0,1]
else:
d = [0] * (num+1)
d[0] = 0
d[1] = 1
for i in range(2,num+1):
if i % 2 ==0:
d[i] = d[i//2]
else:
d[i] = d[i//2] + 1
return d

leetcode338的更多相关文章

  1. [Swift]LeetCode338. 比特位计数 | Counting Bits

    Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the ...

  2. leetcode338—Counting Bits

    Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the ...

  3. LeetCode 338

    Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the ...

  4. LeetCode practice

    子集和问题:给定一组数和一个值,从这组数中选出若干个数使其和为给定的值.这是个NPC问题. 1.https://leetcode.com/problems/counting-bits/#/soluti ...

随机推荐

  1. poj1873(枚举+凸包)

    The Fortified Forest Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 7291   Accepted: 2 ...

  2. nginx——优化 Nginx 站点目录

    1. 禁止解析指定目录下的指定程序 location ~ ^/data/.*.(php|php5|sh|pl|py)$ { # 根据实际来禁止哪些目录下的程序,且该配置必须写在 Nginx 解析 PH ...

  3. 剑指Offer 28. 数组中出现次数超过一半的数字 (数组)

    题目描述 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字.例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}.由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2. ...

  4. L2-016. 愿天下有情人都是失散多年的兄妹(深搜)*

    L2-016. 愿天下有情人都是失散多年的兄妹 参考博客 #include<iostream> #include<cstdio> #include<cstring> ...

  5. 初始化 CSS 样式

    为什么要初始化 CSS 样式 因为浏览器的兼容问题,不同浏览器对有些标签的默认值是不同的,如果没对 CSS 初始化往往会出现浏览器之间的页面显示差异. 当然,初始化样式会对 SEO 有一定的影响,但鱼 ...

  6. zabbix的自动发现、自定义添加监控项目、配置邮件告警

    1.zabbix的自动发现这里的自动发现,所显示出来的是规则的上自动了现 然后 可以对其内容进行相关的配制,如时间或周期 注意:对于单个主机的规则,可以自行添加或删除, 但对于已经添加好了的规则,若需 ...

  7. Map集合、HashMap集合、LinkedHashMap集合、Hashtable集合、Collections工具类和模拟斗地主洗牌和发牌

    1.Map集合概述和特点 * A:Map接口概述  * 查看API可以知道:          * 将键映射到值的对象          * 一个映射不能包含重复的键          * 每个键最多 ...

  8. node day2 vue read html

    app.js var http = require("http"); var fs = require('fs'); var url = require('url'); http. ...

  9. JavaScript 实现打印操作

    一.打印当前页面指定元素中的内容 方式一:直接使用window.print(); (1)首先获得元素的html内容(这里建议如果有样式最好是用内联样式的方式) var newstr = documen ...

  10. 使用maven profile指定配置文件打包适用多环境

    新建maven项目,   在pom.xml中添加 profile节点信息如下: <profiles> <profile> <!-- 开发环境 --> <id& ...