diff --git a/Bit-manipulationTechniques/CountBits/main.cpp b/Bit-manipulationTechniques/CountBits/main.cpp index 553175b..fdd11b6 100644 --- a/Bit-manipulationTechniques/CountBits/main.cpp +++ b/Bit-manipulationTechniques/CountBits/main.cpp @@ -16,12 +16,27 @@ int countBits(int n) return count; } +// Counting Sets Bits: Hack (faster method) +int countBitsHack(int n) +{ + int ans = 0; + while (n > 0) + { + // Removes the last set bit from the current number + n = n & (n - 1); + ans++; + } + + return ans; +} + int main() { int n; cin >> n; cout << countBits(n) << endl; + cout << countBitsHack(n) << endl; return 0; }