Skip to content

Instantly share code, notes, and snippets.

@dryear
Created November 3, 2016 06:25
Show Gist options
  • Select an option

  • Save dryear/e73cad537bea49cb72fec6e530afbb01 to your computer and use it in GitHub Desktop.

Select an option

Save dryear/e73cad537bea49cb72fec6e530afbb01 to your computer and use it in GitHub Desktop.
LeetCode 338. Counting Bits
/**
* https://leetcode.com/problems/counting-bits/
*
* O(n) runtime, O(1) space
*
* use DP to solve this question
*
* assume k is a multiple of two
* then for k < i < 2k, f(i) = 1 + f(i - k)
* where f(x) means the number of 1's in x's binary representation
*/
public class Solution {
public int[] countBits(int num) {
if (num == 0) {
return new int[] { 0 };
}
int[] res = new int[num+1];
res[1] = 1; // initialization
for (int i = 2, weight = 1; i <= num; i++) {
if (i < 2 * weight) {
res[i] = 1 + res[i-weight];
} else {
weight *= 2;
res[i] = 1;
}
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment