338. Counting Bits
来源:互联网 发布:淘宝10元包邮怎么赚钱 编辑:程序博客网 时间:2024/06/07 02:01
1.Question
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]
.
class Solution {public: vector<int> countBits(int num) { vector<int> res(num+1); if(num == 0) return res; res[1] = 1; int flag = 1; int label_pre = 1; int label_cur = 2; while(2*flag < num+1) { if(flag*4 <= num+1) { for(int i = 0; i < flag; i++) { res[label_cur] = res[label_pre]; res[label_cur+1] = res[label_pre]+1; label_pre +=1; label_cur +=2; } } else { for(int i = 0.5*num+0.5-flag; i > 0; i--) { res[label_cur] = res[label_pre]; res[label_cur+1] = res[label_pre]+1; label_pre +=1; label_cur +=2; } if(num%2 == 0) res[label_cur] = res[label_pre]; } flag *= 2; } return res; }};
3.Note
a. 这个题有个技巧,你把所有的数字转化为二进制之后会发现:
1,2,3,4,5,6,7,8,9...为1, 10, 11, 100, 101, 110, 111, 1000, 10001....
这样的话,把他们分成[1], [2 3], [4 5 6 7], [8 9 ...15]
对应的二进制是[1], [10 11], [100 101 110 111], [1000 1001 ...1111]
他们每一组二进制数字可以由前一组二进制数字获得,
比如在1后分别加0,1则是10,11
在10 11后各自分别加0,1则是100,101, 110,111。
找到规律后就是如何编程的问题了。
一组一组地添加,开始的条件是:下一组有需要填充的位置,即 num - flag*2 + 1 >0 (等同于2*flag < num+1)
需要整组添加还是只需要填充一部分,则看下一组的个数是否小于剩下的空余位置,即 num - flag*2 +1 >= flag*2(等同于flag*4 <= num+1)
此外还要考虑num是偶数还是奇数,如果num是偶数,则需要填充的位置应该是奇数,处理时要小心。
- [leetcode] 338. Counting Bits
- 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCodeOJ:338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- 338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- 338. Counting Bits
- (leetcode) 338. Counting Bits
- Swift 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- 心路历程
- 第9章 进程间通信
- Wireshark过滤器使用规则介绍
- HDU 4126 Genghis Khan the Conqueror(树形dp,MST,破坏原有最小生成树边后的最小生成树代价)
- UVA 116 Unidirectional TSP 动态规划+类似数塔
- 338. Counting Bits
- About Core Animation
- ---使用HttpSession防止表单重复提交
- DMA
- Codeforces Round #344 (Div. 2)D. Messenger【kmp】
- Android自定义控件之日历控件
- sql create table index
- SpringMVC 上传文件出现 Provisional headers are shown 和 response 数据 无法输出问题
- node之hello world