LeetCode-Counting Bits
来源:互联网 发布:json在线处理 编辑:程序博客网 时间:2024/06/16 01:28
1. Counting Bits (Medium)
Description
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.
Analysis
我们可以发现每个i值都是i&(i-1)对应的值加1,这样我们就可以写出代码如下:
代码:
class Solution {public: vector<int> countBits(int num) { vector<int> result(num + 1, 0); for (int i = 1; i <= num; ++i) { result[i] = result[i & (i - 1)] + 1; } return result; }};
阅读全文
0 0
- leetcode:bits:Counting Bits(338)
- [leetcode] 338. Counting Bits
- 【LeetCode-338】Counting Bits
- leetcode-338-Counting Bits
- leetcode:Counting Bits
- [C]LeetCode:Counting Bits
- LeetCode Counting Bits
- leetcode 338. Counting Bits
- leetcode Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- Leetcode 338 Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode之Counting Bits
- LeetCode 338. Counting Bits
- LeetCode 338 :Counting Bits
- leetcode--Counting Bits
- [leetcode-338]Counting Bits
- 除了gcc外,其他的一些编译器
- Metasploit 整理笔记
- 带有进度条文件上传(UploadFile+AJAX+监听器)
- poj 3984 迷宫问题
- 运算放大器常见的指标
- LeetCode-Counting Bits
- 包装类型的数据比较
- Javascript 设计模式
- Java跨平台特性
- Solidworks编辑零件卡死解决方案
- 正式培训的第一天
- 【Scikit-Learn 中文文档】内核近似
- WingIDE6破解
- linux 内核 下 读写 文件