Easy solution to understand


  • 0
    L

    Firstly,we just calculate the number of 1's in their binary representation separately, then we can know that,if (i&1) then number[i] = number[i-1]+1,else number[i] = number[i/2]

    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> ans(num+1,0);
            for (int i = 1; i <= num; ++ i) {
                if (i&1) ans[i] = ans[i-1]+1;
                else ans[i] = ans[i>>1];
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.