leetcode 338. Counting Bits
来源:互联网 发布:男士帽子 知乎 编辑:程序博客网 时间:2024/04/26 05:56
分析
打算用动态规划,所以先找x和x-1的规律:
0
1
10
11
100
101
110
111
1000
1001
1010
1010010100101
1010010100110
111
1000
f(x) 表示x二进制表示中1的个数, m表示从右往左第一个0的位置(从0开始计数)。
找数字x-1 从右往左第一个0的位置m;
f(x) = f(x-1) - m + 1;
我们认为7这样的数字的二进制表示中没有0,如果x-1的二进制表示中没有找到0,则:
f(x) = 1;
代码
public class Solution { public int findZeroFromRight(int n){ int ans = 0; while(n % 2 == 1){ n = n >> 1; ans++; } if(n == 0) return -1;//表示n的二进制表示中没有0 else return ans; } public int[] countBits(int num) { int ans[] = new int[num+1]; ans[0] = 0; for(int i = 1; i <= num; i++){ int m = findZeroFromRight(i-1); if(m == -1){ ans[i] = 1; } else{ ans[i] = ans[i-1] - m + 1; } } return ans; }}
0 0
- [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
- 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
- LeetCode-338. Counting Bits
- leetcode-338. Counting Bits
- Leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- FindBugsFilter的用法
- 数据结构A之链表的简单操作
- 内联函数和成员函数区别
- Android 最火的快速开发框架XUtils
- JUnit assertEquals 两个对象或集合类型
- leetcode 338. Counting Bits
- hdu 2157(矩阵快速幂)
- 定向网页爬虫经验总结
- android 4.0.3和4.0.4上webview只显示一屏问题的定位
- 走马灯效果总结
- C++打印日志功能设计
- CSS行高——line-height
- 使用view来制作分割线
- Flume结构简要分析