Something like 89. Gray Code,find the pattern


  • 0
    O
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int>res(num+1,0);
            int base=1;
            int k=1;
            while(k<=num){
            for(int j=0;j<base&&k<=num;j++)
                    res[k++]=res[j]+1;
                base<<=1;
            }
            return res;
            
        }
    };
    

    like Gray Code, we can find the pattern

    0 - 0

    1 - 1

    2 - 1

    3 - 2

    4 - 1

    5 - 2

    6 - 2

    7 - 3

    8 - 1

    Each value of the array [0,2^(i-1)-1] plus 1 we can get the array [2^(i-1),2^i-1] .For example,the array[4,7] is array[0,3]+1.


Log in to reply
 

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