Easy understood C++ code

  • 0
    class Solution {
        vector<int> countBits(int num) {
            vector<int> res(num+1, 0);
            for (int i = 1;i <= num;i++){
                if((i&1) == 0)
                    res[i] = res[i/2];
                    res[i] = res[i/2]+1;
            return res;

    As we all know an even number's last digit must be a 0, so we can ignore this zero and right shift it with one place and get the answer;For odd numbers, the last digit is 1, and we can do the same thing and add 1 to the answer;

Log in to reply

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