https://leetcode-cn.com/problems/counting-bits/solution/
Set the last 1 to 0: The
proof is still very simple. Suppose a string of data is:
x=……1……,
the front of 1 is unknown, the back of 1 is all 0, and the result of x-1 is:
x -1=……0……,
the position of 0 is the same as the position of 1 above, the front of 0 is the same as the above, and the back of 0 is all 1, so when performing bitwise operations, you can obviously find that the final result is x The number before 1 in the middle does not change, the numbers after 1 will all become 0 (including 1. And
, when performing bitwise operations, the following is the point:
i&(i-1)==0 actually count it first (i- 1) === It still needs attention.
This topic is still very interesting:
in fact, the order of the numbers is artificially arranged. When we want to calculate the number of numbers in it, we don’t need to pay attention to the order at all. .
like the questions, the most ingenious method of dynamic programming, is the first place as a binary expansion.
class Solution {
public:
vector<int> countBits(int num) {
int highbit=0;
vector<int> ans(num+1);
for(int i=1;i<=num;i++){
if((i&(i-1))==0){
highbit=i;
}
ans[i]=ans[i-highbit]+1;
}
return ans;
}
};
This is a small detail, and today I know the power of knuth, I want to buy a programming art to enshrine on the bedside.