【LeetCode-338】 Counting Bits
来源:互联网 发布:第八课网络旅行 编辑:程序博客网 时间:2024/06/06 13:23
原题:
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]
.
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
题目大意:
给一个非负整数num,输出[0,num]间每一个数字的二进制表示中1的个数。
思路:
把前几个值动手写一写,很快就能发现迭代规律,构建出如下图的二叉树。
代码:
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* countBits(int num, int* returnSize) { int* p; *returnSize = num+1; p = (int*)malloc(*returnSize*sizeof(int)); if (num == 0){ p[0]=0; return p; } p[0]=0; p[1]=1; for (int i = 2 ; i <= num ; i++){ if (i % 2 == 0){ p[i] = p[i/2]; }else{ p[i] = p[i/2]+1; } } return p;}
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
- Android Studio 学习 2
- android Spinner控件详解
- Java的类属性和实例属性
- mybatis 注解和xml的使用
- PHP中实现页面刷新或跳转的方法
- 【LeetCode-338】 Counting Bits
- 孤儿进程和僵尸进程
- Linux-Tomcat进程CPU使用率100%原因分析
- android仿苹果SwitchButton效果的实现
- 笔记 - Android - 6.上下文Context API
- ubuntu中安装docker
- 华宇拼音输入法在英雄联盟中没有输入框
- git版本控制工具的学习
- 2016年3月浙江理工大学校赛E 题解