[LeetCode]338. Counting Bits
2016-04-03 11:28
501 查看
Problem 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.[]https://leetcode.com/problems/counting-bits/]
思路
DP。对于一个数,如果他是偶数,那它二进制后含有‘1’的个数与左移一位之后含有‘1’的个数相同,如果是奇数,则加1。
例如:
偶数1100110中含有的1与110011相同
奇数1100111中含有的1比110011多1.
Code
package q338; public class Solution { public int[] countBits(int num) { int[] ans=new int[num+1]; ans[0]=0; for(int i=1;i<=num;i++){ ans[i]=ans[i-1]>>1+i%2; } return ans; } }
相关文章推荐
- RED HAT5安装VMWARE TOOLS报错解决办法
- SIFT特征提取分析
- Python编程-数据库-利用PyMysql访问windows下的MySql数据库
- 链表设置
- CSU 1715(暴力)
- Java 正则表达式
- 几个有关iOS的几个常见问题-----RunTime
- GetOpenFileName 选择文件夹的解决方法
- nginx的通用配置
- 抓高送转
- 《构建之法》读书笔记
- ssh连接的时候很慢问题解决
- Node.js 应用跑得更快 10 个技巧
- I_PCM模式学习笔记
- JavaScript常用对象Array(2)
- C语言中如何解决重复include的问题
- MySQL命令行登录的例子
- 写给jos一个羞辱我的运维高管
- 正则表达式基础和使用及常用表达式
- 博客搬家辣!http://www.cnblogs.com/beiyuoi/