Very simple Java DP solution using bitwise operators (4ms)


  • 3
    M
    public class Solution {
        
        public int[] countBits(int num) {
            int[] tab = new int[num+1];
            for(int i = 1; i<=num; i++){
                // add last bit (i&1) with the number of bits in i/2 (equivalent to i>>1)
                tab[i] = (i & 1) + tab[i>>1];
            }
            return tab;
        }
    }

Log in to reply
 

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