LeetCode-338:Counting Bits
来源:互联网 发布:查看被占用的端口 编辑:程序博客网 时间:2024/06/11 00:39
原题描述如下:
Given a non negative integer number num. For every numbersi 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]
题意
:给定一个数字,求从0到该数字,每一个数字对应二进制包含1的个数。
解题思路:移位。例子:5对应的二进制位101,则其位数为101向右移动以为的到的10包含的位数加上101的最低位(是1则总数加1,否则不加)
Java代码:
public class Solution {public int[] countBits(int num) {
if(num == 0)return new int[]{0};
if(num == 1)return new int[]{0, 1};
int[] dp = new int[num+1];
dp[1] = 1;
for(int i=2; i<dp.length; ++i){
dp[i] = (i&1) + dp[i>>1];
}
return dp;
}
}
0 0
- leetcode:bits:Counting Bits(338)
- 【LeetCode-338】Counting Bits
- leetcode-338-Counting Bits
- Leetcode 338 Counting Bits
- LeetCode 338 :Counting Bits
- [leetcode-338]Counting Bits
- 【LeetCode-338】 Counting Bits
- LeetCode 338 Counting Bits
- Counting Bits leetcode 338
- [LeetCode 338] Counting Bits
- LeetCode-338:Counting Bits
- LeetCode-338:Counting Bits
- LeetCode[338] Counting Bits
- LeetCode#338 Counting Bits
- LeetCode 338 Counting Bits
- LeetCode 338 Counting Bits
- Leetcode #338 Counting Bits
- Leetcode 338 Counting Bits
- Discuz! 更改用户名长度(代码和数据库字段)
- 基于python的数字判断程序和字符串判断程序
- 数据驱动测试一:使用TestNG进行数据驱动
- C语言中 fp = fopen(filename, “rb”); 那个rb是什么意思啊
- AC again
- LeetCode-338:Counting Bits
- Swift类型推测在可选调用中的小提示
- C#关键字—yield
- 欢迎界面倒计时
- 144. Binary Tree Preorder Traversal
- GPIO
- 欢迎使用CSDN-markdown编辑器
- LeetCode-难题集之Merge Two Sorted Lists
- Hdu1754 I Hate It 线段树、单点更新+区间最值