Counting Bits - Java, 2ms


  • 1
    V
        public int[] countBits(int num) {
            int[] result = new int[num+1];
            int power, nextPower, p, i;
            result[0] = 0;
            power = nextPower = 1;
            p = 0;  /* Start with pow(2,0) */
            i = 1; /* Fill array from i = 1 */
            while( i <= num ) {
                if( i < nextPower ) {
                    result[i] = result[i-power] + 1;
                    i++;
                }
                else {
                    power = nextPower;
                    nextPower <<= 1;
                }
            }
            return result;
        }
    

Log in to reply
 

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