【LeetCode】Counting Bits 解题报告
来源:互联网 发布:c语言取反加一 编辑:程序博客网 时间:2024/05/19 13:09
【LeetCode】Counting Bits 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/counting-bits/#/description
题目描述:
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]
.
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Ways
这个题用DP的方法。把第i个数分成两种情况,如果i是偶数那么,它的二进制1的位数等于i/2中1的位数;如果i是奇数,那么,它的二进制1的位数等于i-1的二进制位数+1,又i-1是偶数,所以奇数i的二进制1的位数等于i/2中二进制1的位数+1. 所以上面的这些可以很简单的表达成answer[i] = answer[i >> 1] + (i & 1)
。
public class Solution { public int[] countBits(int num) { int[] answer = new int[num+1]; answer[0] = 0; for(int i = 1; i < answer.length; i++){ answer[i] = answer[i >> 1] + (i & 1); } return answer; }}
Date
2017 年 4 月 25 日
0 0
- 【LeetCode】Counting Bits 解题报告
- [leetcode] 338. Counting Bits 解题报告
- LeetCode 338.Counting Bits 解题报告
- LeetCode解题报告 338. Counting Bits [medium]
- leetcode解题报告:338. Counting Bits
- [Leetcode] 338. Counting Bits 解题报告
- Counting Bits解题报告
- LeetCode---Counting Bits解题分析
- LeetCode-Reverse Bits-解题报告
- LeetCode-Number of 1 Bits-解题报告
- [leetcode] 190. Reverse Bits 解题报告
- 【LeetCode】Number of 1 Bits 解题报告
- [Leetcode] 190. Reverse Bits 解题报告
- leetcode:bits:Counting Bits(338)
- [leetcode] 338. Counting Bits
- 【LeetCode-338】Counting Bits
- leetcode-338-Counting Bits
- leetcode:Counting Bits
- Java解析复杂嵌套JSON数据格式代码,提取出来所有的key和value。亲测代码可用
- ajax请求返回了两个重复json对象
- 集合框架-键盘录入学生按照总分从高到底输出
- JAVA的Date类和Calendar类
- AutoCompleteTextView 设置了点击事件需要点击两下解决办法
- 【LeetCode】Counting Bits 解题报告
- Windows安装多个版本JDK,如何灵活指定当前想用JDK版本?
- 如何访问github上的HTML代码对应的页面。
- JAVA8 十大新特性详解
- Zookeeper分布式队列的实现
- android Activity管理类(全局管理Activity)
- 每周荐书:SLAM、Vue2、爬虫(评论送书)
- 宽度优先搜索与深度优先搜索
- 动态库链接问题解决