Easy C++ solution time O(n)


  • 2
    Y
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> result (num+1,0);
            for(int i = 0; i <= num/2; i++){
                result[2*i] = result[i];
                result[2*i + 1] = result[i] + 1;
            }
            return result;
        }
    };

  • 0
    G
    class Solution {
    public:
        vector<int> countBits(int num) {
            if (num == 0) return {0};
            vector<int> result (num+1,0);
            result[1] = 1;
            for(int i = 1; i <= num/2; i++){
                result[2*i] = result[i];
                result[2*i + 1] = result[i] + 1;
            }
            return result;
        }
    };

  • 0
    Y

    sorry, I've made a mistake in my code, just change i = 1 to i = 0 and the program will work well. The judgement for num == 0 and 1 are not needed.


Log in to reply
 

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