338. Counting Bits
来源:互联网 发布:云像数字 知乎 编辑:程序博客网 时间:2024/05/17 07:32
题目描述:
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.
本题要我们列出从0到num的二进制表示中1的个数,通过观察我们可以知道,当偶数i加上1时,1的个数也加1,但当奇数i加上1时,由于进位,1的个数可能不变甚至减少。我们先假设每个数的1的个数都在上一个数的基础上加1,那么当这个数为偶数时,1的个数要减去1,并且右移一位,直到这个数不再是偶数。
代码:
class Solution {public: vector<int> countBits(int num) { vector<int> bits(num+1, 0); for (int i = 1; i <= num; i++) { int temp = i; bits[i] = bits[i-1] + 1; while (temp % 2 == 0) { bits[i] -= 1; temp /= 2; } } return bits; }};
阅读全文
0 0
- [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
- D_D系统构建-文件写入方法
- Spring Data JPA+kkpager实现分页功能
- 数据结构-笔记(第一章)
- 用lua扩展你的Nginx(写的非常好)
- 数据库系统概念(机械工业出版社,第六版)复习——第二章:关系模型简介
- 338. Counting Bits
- 20个最佳的Java集合框架面试题目
- 北方大学 ACM 多校训练赛 第十五场 数字游戏
- React性能检测和优化
- curl模拟post请求提交
- iOS CADisplayLink(绘制动画)
- MongoDB 3.x java基本操作-CRUD
- html5解决大文件断点续传
- 阿里云上配置web环境 jdk+tomcat+mysql