c++ noob solution


  • 0
    R

    vector<int> countBits(int num) {

        /*
         *  1.if pre num's last bit is 0, d[i]=d[i-1]+1
         *  2.if pre num's last bit is 1, d[i]=d[i-1] - (i-1)>>n + 1 , so n is from right to left 1's count before first 0
         *  such as 1110111,next number is 1111000
         */
        vector<int> vec;
        vec.push_back(0);
        for(int i=1; i<=num;i++)
        {
            if((i-1)&1==0)vec.push_back(vec[i-1]+1);
            else
            {
                int x=i-1;
                int cnt=0;
                while(x&1==1)
                {
                    x>>=1;
                    cnt++;
                }
                vec.push_back(vec[i-1]-cnt+1);
            }
        }
        return vec;
    }

Log in to reply
 

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