LeetCode 338. Counting Bits
来源:互联网 发布:sprin 源码 编辑:程序博客网 时间:2024/06/06 14:04
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]
.
题目内容:
题目给出一个非负整数num,让我们分别求出[0, num]这个区间内的所有整数对应二进制数当中1的个数。例如[0, 5]区间中所有整数的二进制中1的个数如下表:
解题思路:
这一道题我们可以遍历[0, num]中的所有整数,转换成二进制,再计算当中’1’的个数,这样的复杂度是
这道题在LeetCode中是属于动态规划(Dynamic Programming)的题目,所以我们可以尝试从动态规划的角度出发。假如用result[i]表示非负整数i的二进制表示中’1’的个数,那么result[i]应该怎样通过result[0]…result[i - 1]算出来。我们知道,在十进制中,一个数字除以2(整数除法),相当于将其二进制数往右移一位,例如
所以,我们是否能够通过result[i / 2]来计算出result[i]。答案是可以的,假如i的二进制位数为j,那么通过result[i / 2]我们可以得到前面
所以这个动态规划中,result[0]=0,状态迁移方程为:
代码:
#include <iostream>#include <vector>using namespace std;class Solution {public: vector<int> countBits(int num) { vector<int> result(num + 1); result[0] = 0; for (int i = 1; i <= num; i++) { result[i] = result[i / 2] + i % 2; } return result; }};
0 0
- [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
- (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
- MATLAB随机函数比较
- 配置tomcatserver.xml
- Find All Numbers Disappeared in an Array问题及解法
- NYOJ 722 数独
- 虚拟机编译代码是报 Cannot allocate memory Error
- LeetCode 338. Counting Bits
- linux下mysql开启远程访问权限及防火墙开放3306端口
- Vue从入门到精通(1)--前言、基础知识
- 常见的设计模式
- 字串的连接最长路径查找(使用TreeSet集合的比较器new Comparator(){ }:匿名内部类方法)
- JAVA 转 C++ 必记 PartB
- POJ 1458 Common Subsequence(LCS)
- 文件传输命令scp使用——linux主机传文件到windows主机
- 类似智能购票的demo--进入页面后默认焦点在第一个输入框,输入内容、回车、right时焦点自动跳到下一个,当跳到select时,下拉选项自动弹出,并且可以按上下键选择,选择完成后再跳到下一个。