LeetCode
来源:互联网 发布:国考 知乎 编辑:程序博客网 时间:2024/06/05 15:27
题目
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].
输入一个整数,输出一个数组,数组中的元素为从0到这个整数的每个数字的二进制中有多少个1。
思路
思路(来自 LeetCode 讨论区大佬 ):
1111 相比于 111 多了一个1,1110 相比于 111 ,1的个数相同,而 1111 或者 1110 右移一位得到111。
根据这个特性,只需要判断最后一位是不是1即可
代码
public int[] countBits(int num) { if (num < 0) { return null; } int[] res = new int[num + 1]; for (int i = 0; i <= num; i++) { res[i] = res[i >> 1] + (i & 1); } return res;}
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- 哪些码农小习惯预示着高薪资?
- Python: __future__ 模块
- ArrayList、Vector、LinkedList的区别及其优缺点?
- 【Spring boot】第一个项目 Springboot + mysql + hibernate
- 全连接层的作用
- LeetCode
- react map遍历时事件无效
- wcf系列学习5天速成——第三天 事务的使用
- 项目当中遇到要获取本月之前的数据列表查询
- 【C#】遍历清空文本框内容
- Python中的Map, Filter和Reduce
- 【Linux】线程安全和可重入函数
- 1001. 会议安排
- 多线程