yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #338. Counting Bits #267

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        res[0] = 0;
        int pow = 1;

        for (int i = 1, t = 0; i <= num; i++, t++) {
            if (i == pow) {
                pow *= 2;
                t = 0;
            } 
            res[i] = res[t] + 1;
        }

        return res;
    }
}

With this, we can only find the math pattern behind it.

yokostan commented 5 years ago

https://leetcode.com/problems/counting-bits/discuss/79615/Simple-Java-O(n)-solution-using-two-pointers