10ms java solution with bit manipulation


  • 0
    S

    public class Solution {
    public int[] countBits(int num) {
    int[] bits = new int[num + 1];
    bits[0] = 0;
    int i,j;

        for(i =1;i<=num;i++) {
            
            if(((i - 1) & 1) == 0) {
                bits[i] = bits[i - 1] + 1;
            } else {
                int combo = i ^ (i - 1);
                combo = (combo + 1) >> 1;
                int diff = (int)(Math.log(combo) / Math.log(2));
                
                bits[i] = bits[i-1] - diff + 1;
            }
        }
        
        return bits;
    }
    

    }


Log in to reply
 

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