LeetCode 338
来源:互联网 发布:dnf提示框源码 编辑:程序博客网 时间:2024/05/22 06:12
LeetCode 338
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].
Solution:
因为是递增,所以可以找res[i] = res[i & (i-1)] + 1的规律
class Solution {public: vector<int> countBits(int num) { vector<int> res(num+1, 0); for (int i = 1; i < num+1; i++) { res[i] = res[i & (i-1)] + 1; } return res; }};
改进:
用bitset,count()函数
class Solution {public: vector<int> countBits(int num) { vector<int> res(num+1, 0); for (int i = 1; i < num+1; i++) { res[i] = bitset<32>(i).count(); } return res; }};
阅读全文
0 0
- LEETCODE 338
- leetcode 338
- LeetCode 338
- 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
- Counting Bits leetcode 338
- [LeetCode 338] Counting Bits
- LeetCode-338:Counting Bits
- Leetcode no. 338
- LeetCode-338:Counting Bits
- LeetCode[338] Counting Bits
- LeetCode#338 Counting Bits
- c语言关键字(上)
- 了解MVC、MVP于MVVM的区别
- Pandas时间序列
- Spring源码之JdbcTemplate中的坑,你中招了吗
- 活用宏定义
- LeetCode 338
- 简单的通信(QUdpSocket、 QTcpSocket、QWebSocket)-----Qt网络
- 自定义View+点击生成随机数
- openedx 配置 SMTP
- 量化投资(二):五日均价策略
- Feign简单入门
- HTML网页+nodejs实现websocket
- 数字图像处理之图像显示基础
- ListView失去焦点怎么处理