Share my O(n) cpp solution


  • 0
    Z
    class Solution {
    public:
    vector<int> countBits(int num) {
        vector<int> result;
        result.push_back(0);
        if(num<=0)
    		return result;
    	
    	
    	int index = 1;
    	for(int i=1;i<=num;i++){
    	    if(i>=2*index)
    			index *= 2;
    		result.push_back(result[i-index]+1);
    		
    	}
    	return result;
    }
    };

Log in to reply
 

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