[LeetCode]338. Counting Bits
来源:互联网 发布:养车软件哪个好 编辑:程序博客网 时间:2024/06/03 20:46
- descrption
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 1
For num = 5 you should return [0,1,1,2,1,2].
- 解题思路
这道题在动态规划的主题中。如果不用动态规划算法,我们只需要将每个number转换为2进制,计算出其中1的数量就好。如果用动态规划算法,就要思考动态规划方程要怎么列。首先观察一下数字的二进制表达
number binary the number of '1'0 0000 01 0001 12 0010 13 0011 24 0100 15 0101 26 0110 27 0111 38 1000 19 1001 210 1010 2-------------------------------可以观察到:如果一个数字是奇数,那么它的二进制表达的1的数量就是它前一个数字的1的数量加一.如果一个数字是偶数,那么他的二进制表达的1的数量就是它除以2这个数字的1的数量。假设a为奇数,b=a-1,b就为偶数,b的二进制表达的最低为一定为0,a比b大一,那么a的二进制表达就是b的二进制表达加1,而不会产生进位,所以a的二进制表达的1的数量是b的1的数量加1。假设a为偶数,b=a/2,用二进制表达,a只是比b末尾多一个0,1的数量还是相同的,所以可以得到动态规划方程:number_1(0) = 0;if i is odd: number_1(i) = number_1(i-1)+1;if i is even: number_1(i) = number_1(i/2);
- 代码如下
class Solution {public: vector<int> countBits(int num) { vector<int> ans; ans.push_back(0); for(int i = 1 ; i <= num; i++){ if(i%2 == 1){ ans.push_back(ans[i-1]+1); } else { ans.push_back(ans[i/2]); } } 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
- Node.js —— 创建TCP服务器
- Java日记
- 【OVS2.5源码解读】datapath的netlink机制
- CNN中感受野的计算
- #随笔之java匿名内部类
- [LeetCode]338. Counting Bits
- 【JavaScript】引擎、运行时
- U-Mail:优秀的linux邮件系统
- C# WinForm常用控件
- HTML(二)
- Java反射泛型应用
- 八大排序算法讲解与比较
- python安装与解析器学习
- C# 1000的阶乘