当前位置:网站首页>338. Bit counting · dynamic programming
338. Bit counting · dynamic programming
2022-07-18 07:53:00 【Xiao Xun wants to be strong】
subject
Give you an integer n , about 0 <= i <= n Each of the i , Calculate its binary representation 1 The number of , Returns a length of n + 1 Array of ans As the answer .
Example

Ideas
Direct traversal
Traversing integers n, Position each element with itself -1, Until 0, There are as many as the number of times 1
Dynamic programming
utilize 0001 0010 0100 1000 Dynamically update the data of each segment
Code
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int countBit(int x)
{
int count = 0;
while(x)
{
x &= (x-1);
count++;
}
return count;
}
int* countBits(int n, int* returnSize){
int * bit_nums = malloc(sizeof(int) * (n + 1));
*returnSize = n + 1;
for(int i = 0; i <= n; i++)
{
bit_nums[i] = countBit(i);
}
return bit_nums;
}
Dynamic programming
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
/*
*int* countBits(int n, int* returnSize)
int* countBits: seek 0-n In the integer of bit position 1 The number of
int n: Integers
int* returnSize: Length of return value
Return value :bit Number of bits to go Array
*/
int* countBits(int n, int* returnSize) {
int* bits = malloc(sizeof(int) * (n + 1));
*returnSize = n + 1;
bits[0] = 0;
int highBit = 0;
for (int i = 1; i <= n; i++) {
if ((i & (i - 1)) == 0) {
highBit = i;
}
bits[i] = bits[i - highBit] + 1;
}
return bits;
}
Time and space complexity

边栏推荐
- 406·根据身高重建队列·贪心
- Matlab:拆分数据集 splitEachLabel() 的用法
- 2022中国移动创客马拉松大赛物联网专题赛开赛啦
- Query distance according to longitude and latitude and sort by distance
- Race · 6116 · calculate the value of Boolean binary tree · recursion
- LAN attack and network device security configuration
- 每日一题·735.行星碰撞·栈模拟
- Two way merge sort summary
- 每日一题·648.单词替换·前缀树
- Matlab:交换矩阵的两行(列)
猜你喜欢
随机推荐
二叉树(BinaryTree)和堆(Heap)的知识点整理
【详细教程】一文参透MongoDB聚合查询
SAR图像:拟合杂波时常用的分布
Think of multithreading concurrency is guilty? Let's consolidate these basic knowledge of threading first!
实现一下几个简单的loader
Compétition · 6116 · calcul de la valeur de l'arbre binaire booléen · récursion
1. Huawei machine test question record
CAS与AQS简单理解
How can cloud digital innovation shape the happiness of a city?
338.比特位计数·动态规划
Matlab:搭建神经网络
Openharmony related knowledge learning
(open source project) abattoir unity game
打脸一题
FrameWork源码——Binder 驱动解析
软件架构与设计(六)-----层次结构体
Matlab求正态函数积分,积分对应的分位点
竞赛·6116·计算布尔二叉树的值·递归
软件架构与设计(九)-----基于组件的架构
Allure测试报告怎么设置









