My Java 3ms solution. No DP and no bit operation.


  • 0
    J
    public class Solution {
        public int[] countBits(int num) {
            int[] result = new int[num + 1];
            result[0] = 0;
            int refNum = 0;
            for (int i = 1; i <= num; i++) {
                if ((i & (i - 1)) == 0) {
                    result[i] = 1;
                    refNum = i;
                }
                else {
                    int temp = i - refNum;
                    result[i] = 1 + result[temp];
                }
            }
            
            return result;
        }
    }
    

Log in to reply
 

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