g0301_0400.s0338_counting_bits.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0301_0400.s0338_counting_bits;
// #Easy #Dynamic_Programming #Bit_Manipulation
public class Solution {
public int[] countBits(int num) {
int[] result = new int[num + 1];
int borderPos = 1;
int incrPos = 1;
for (int i = 1; i < result.length; i++) {
// when we reach pow of 2 , reset borderPos and incrPos
if (incrPos == borderPos) {
result[i] = 1;
incrPos = 1;
borderPos = i;
} else {
result[i] = 1 + result[incrPos++];
}
}
return result;
}
}