338. Counting Bits
来源:互联网 发布:虎嗅网源码下载 编辑:程序博客网 时间:2024/05/16 16:00
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]
.
首先,直接移动计算的时间复杂度太高了,不用考虑。
然后想到n&(n-1)操作可以实现计算二进制中1的个数。
class Solution {public: vector<int> countBits(int num) { vector<int>v(num+1,0); for(int i=1;i<=num;i++){ int t=i,n=0; while(t){ t=t&(t-1); n++; } v[i]=n; } return v; }};
AC之后,又去看了下别人的思路。还有个最快的方法。
即等于n-1的1的个数加上最右边的一位。
class Solution {public: vector<int> countBits(int num) { vector<int>v(num+1,0); for(int i=1;i<=num;i++){ v[i]=v[i>>1]+i&1; } return v; }};
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
- javascript自定义右键菜单,js自定义右键删除——和派孔明
- 网易新闻部分框架
- MongoDB初探--安装和启动
- windows编程笔记(win32编程)以及其在游戏开发中的作用
- python运算符优先级
- 338. Counting Bits
- 2016年,C语言该怎样写
- 音视频同步原理
- git学习笔记
- 视角
- opencv Mat子矩阵赋值小tip
- 103 保序回归 isotonic regression
- 计算机重复启动问题原因及修复
- 使用cJSON解析JSON字符串