您的位置:首页 > 其它

[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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: