Given an integer n, return an array ans of length n + 1 such that for each i **(0 <= i <= n) , ans[i] is the number of 1 's in the binary representation of i.
Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
答案
找规律,奇数的二进制的1个数,与它的一半有关。如3的二进制为11,而1的二进制为01,这相当于1左移1位,然后加一。偶数的二进制的1个数,与它的一半一样,如4的二进制为100,而2的二进制为10,这相当于2左移一位。
go
func countBits(n int) []int {
res := make([]int, n+1)
res[0] = 0
for i := 0; i <= n; i++ {
if i & 1 == 1{
res[i] = res[i >> 1] +1
}else {
res[i] = res[i >> 1]
}
}
return res
}
cpp
class Solution {
public:
vector<int> countBits(int n) {
vector<int> res(n+1);
for(int i=1;i<=n;i++){
if(i&1){
res[i]=res[i-1]+1;
} else {
res[i]=res[i/2];
}
}
return res;
}
};