Friday, September 1st

 Counting Bits

Given a number n, return an array of length n+1 such that for each index, the array gives the number of 1's in the index's binary representation

Drill  Bits

The observation is that for a given number x, if x is even, then the number of ones is the same as x/2, because you're just swapping between which of 2 bits are set to 1.

Similarly, if x is odd, then the number of bits is equal to the floor(x/2) + 1, because like before, you're just switching with even bit is on, plus adding an extra bit for the remainder

To code, we first start out with the base case 0

    vector<int> countBits(int n) {
vector<int> ans;
ans.push_back(0);
if(n==0) return ans;
        ...
    }

Then we iterate through the remaining input values n.  If the number is even, we add the number of ones in half the value, otherwise we add the number of ones in half the value, plus an extra

for(int i=1; i<=n; i++) {
if(i%2==0) {
ans.push_back(ans[i/2]);
} else {
ans.push_back(ans[i/2]+1);
}
}

Finally return the result

    vector<int> countBits(int n) {
            ...
            return ans;
    }

A little testy, but lots of different interesting solutions for the problem.  A tougher easy than most

Full code below

    vector<int> countBits(int n) {
vector<int> ans;
ans.push_back(0);
if(n==0) return ans;

for(int i=2; i<=n; i++) {
if(i%2==0) {
ans.push_back(ans[i/2]);
} else {
ans.push_back(ans[i/2]+1);
}
}

return ans;

} 

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th