2ms Java easy to read solution


  • 0
    S

    The idea is so simple, as long as you get to know how binary bits build up a decimal number.
    For example , it a = 8 , its binary bits will be 1000, and we know that b = 4, b = 100. So it is easy that we can know, if count(b) == n, then count(2b) = n, and count(2b + 1) = n + 1

    public class Solution {
        public int[] countBits(int num) {
            int[] counts = new int[num + 1];
            counts[0] = 0;
            for (int i = 1; i <= num; i++) {
                if (i % 2 == 0) {
                    counts[i] = counts[i / 2];
                } else {
                    counts[i] = counts[i / 2] + 1;
                }
            }
            
            return counts;
        }
    }
    

Log in to reply
 

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