Skip to content

Commit

Permalink
write faster method to count the number of set bits in a given intege…
Browse files Browse the repository at this point in the history
…r in python
  • Loading branch information
justanindieguy committed Jan 31, 2023
1 parent 5bcba71 commit ae5080e
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Bit-manipulationTechniques/CountBits/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,21 @@ def count_bits(n: int):
return count


def count_bits_hack(n: int):
ans = 0

while n > 0:
n = n & (n - 1)
ans += 1

return ans


def main():
n = int(input())

print(count_bits(n))
print(count_bits_hack(n))


if __name__ == "__main__":
Expand Down

0 comments on commit ae5080e

Please sign in to comment.