g0301_0400.s0338_counting_bits.Solution.cs Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-all Show documentation
Show all versions of leetcode-in-all Show documentation
104 LeetCode algorithm problem solutions
The newest version!
namespace LeetCodeNet.G0301_0400.S0338_counting_bits {
// #Easy #Top_100_Liked_Questions #Dynamic_Programming #Bit_Manipulation #Udemy_Bit_Manipulation
// #Big_O_Time_O(num)_Space_O(num) #2024_01_07_Time_67_ms_(98.82%)_Space_42.1_MB_(22.68%)
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;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy