4 lines Solution by C++


  • 0
    Z

    as we know:
    0: 0 0 0 0——————0
    1: 0 0 0 1——————1+dp[0...2^(1-1)]
    2: 0 0 1 0——————1+dp[0...2^(2-1)]
    3: 0 0 1 1
    4: 0 1 0 0——————1+dp[0...2^(3-1)]
    5: 0 1 0 1
    6: 0 1 1 0
    7: 0 1 1 1
    8: 1 0 0 0——————1+dp[0...2^(3-1)]
    9: 1 0 0 1
    10:1 0 1 0
    11:1 0 1 1
    12:1 1 0 0
    13:1 1 0 1
    14:1 1 1 0
    15:1 1 1 1
    so:
    vector<int> countBits(int num)
    {
    vector<int > result(num+1,0);
    for(int i=1;i<=num;i++)
    result[i] =1 + result[i-pow(2,(int)(log(i)/log(2)))];
    return result;
    }


Log in to reply
 

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