338. Counting Bits
来源:互联网 发布:新卡购3.0外包系统源码 编辑:程序博客网 时间:2024/06/06 00:23
位计数:给定一个数num,求从0-num之间每个数字的二进制位中1的个数。
要求:
1.时间复杂度是O(n)
2.空间复杂度也是O(n)
以上两个要求也就限制了我们不能使用简单的暴力求解的方法去解决该问题,必须去总结数据中的规律,找到更简单的方法。
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
......
假设一个数有n位,那么该数的二进制位中1的个数等于最后一位中1的个数和前n-1位所对应的数字的二进制位中1的个数之和。
即numBits[i] = numBits[i>>1] + i%2
有了这个公式,问题迎刃而解,如下图所示的代码。
提交结果如图所示:
阅读全文
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
- 安卓一些操作
- 如果想用mybaits逆向多个条件一起查询就用
- 人群场景分析--Slicing Convolutional Neural Network for Crowd Video Understanding
- android 实现由下至上弹出并位于屏幕底部的提示框
- redis数据持久化
- 338. Counting Bits
- X86 XSAVEOPT 指令详解
- Oracle数据库导入/导出
- Java与J++、J#、C#的历史-简笔
- Android 增加GMS包后提示权限问题
- 手机web端唤醒qq客户端以及电脑web端唤醒qq客户端
- SDK将彻底颠覆开发者的价值观?
- C++指针与引用
- Mysql的各种时间类型的区别以及使用场景