""" 0191.1 - Number of 1 Bits - Solution 1 - Bit Shift and Count """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def hammingWeight(self, n: int) -> int:
"""Number of 1 Bits Function"""
count = 0
while n:
count += n & 1
n >>= 1
return count
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().hammingWeight(11)) # 3
print(Solution().hammingWeight(128)) # 1
print(Solution().hammingWeight(2147483645)) # 30
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 0191.2 - Number of 1 Bits - Solution 2 - Brian Kernighan's Algorithm """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def hammingWeight(self, n: int) -> int:
"""Number of 1 Bits Function"""
count = 0
while n:
n &= n - 1
count += 1
return count
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().hammingWeight(11)) # 3
print(Solution().hammingWeight(128)) # 1
print(Solution().hammingWeight(2147483645)) # 30
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()