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. Fiddler常用命令

    几个常用的命令行方法使用: 查找对应响应码的数据包或请求类型的数据包: 输入“=post”将选择post的数据包并用蓝色底标色 输入:=502 查找服务器返回是图片类型的请求 输入 select im ...

  2. 团队项目(MVP------新能源汽车无线充电管理网站)(个人任务1)

    个人任务:1.设计问卷调查了解电动车目前的市场需求情况 2.收集问卷,并且进行总结和分析 3.后台管理系统界面的登录和注册界面的编写(主要用到html,css,javascript,其中用户的合法性检 ...

  3. 使用元类 编写ORM

    元类 一句话: 元类定制类的创建行为 知识点 1.类的创建: python这种动态语言,函数和类的定义,不是编译时定义的,而是运行时动态创建的. Python解释器遇到class定义时,仅仅是扫描一下 ...

  4. CodeForces - 660D:Number of Parallelograms (问N个点多少个平行四边形)

    pro:给定N个点,问多少个点组成了平行四边形.保证没有三点共线. sol:由于没有三点贡献,所以我们枚举对角线,对角线的中点重合的就是平行四边形.如果没说保证三点不共线就不能这么做,因为有可能4个点 ...

  5. 通过父元素的hover控制子元素的显示

    .searbar_content_box:hover .searchBar_checked_detail_box{ display:block}

  6. java-Collection集合、List集合、Vector集合和迭代器Iterator、ListIterator的使用

    1.对象数组的概述和使用 * A:案例演示 * 需求:我有5个学生,请把这个5个学生的信息存储到数组中,并遍历数组,获取得到每一个学生信息. * Student[] arr = new Student ...

  7. 用virtualenv建立独立虚拟环境 批量导入模块信息

    pip3 install virtualenv mkdir env/env1 source bin/activate pip3 freeze >requirements.txt or pipre ...

  8. Centos7.4安装配置haproxy和Keepalived

    系统版本是centos7.4的 [root@data-1-1 ~]# cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core) [roo ...

  9. 对数据进行GZIP压缩或解压缩

    /** * 对data进行GZIP解压缩 * @param data * @return * @throws Exception */ public static String unCompress( ...

  10. css 样式控制文本过长实现省略号

    css 样式控制文本过长实现省略号 .topicTitle{ text-overflow: ellipsis; max-width: 75%; overflow: hidden; white-spac ...