C++ solutions easy to understand


  • 0
    C
    class Solution {
    public:
        vector<int> countBits(int num) {
            int arr[num+1];
            arr[0] = 0;
            int step = 0, rem = 1;
            for(int i = 1; i <= num; i++){
                arr[i] = arr[i-rem] +1; // example 00000101 = 00000001 + (1), rem is the length between two numbers
                if(step == 0){
                    rem *= 2;
                    step = rem;
                }
                step--;
            }
            vector<int> array(arr, arr+num+1);
            return array;
        }
    };

Log in to reply
 

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