diff --git a/src/main/java/com/leetcode/easy/NumberOf1Bits191.java b/src/main/java/com/leetcode/easy/NumberOf1Bits191.java new file mode 100644 index 0000000..83728d0 --- /dev/null +++ b/src/main/java/com/leetcode/easy/NumberOf1Bits191.java @@ -0,0 +1,19 @@ +// Tags: Bit Manipulation, Divide and Conquer +package com.leetcode.easy; + +public class NumberOf1Bits191 { + /** + * Time complexity: O(1) + * Space complexity: O(1) + */ + public int hammingWeight(int n) { + int res = 0; + while (n != 0) { + if (n % 2 == 1) { + res++; + } + n = n >> 1; + } + return res; + } +} diff --git a/src/test/java/com/leetcode/easy/NumberOf1Bits191Test.java b/src/test/java/com/leetcode/easy/NumberOf1Bits191Test.java new file mode 100644 index 0000000..2a8e3ae --- /dev/null +++ b/src/test/java/com/leetcode/easy/NumberOf1Bits191Test.java @@ -0,0 +1,39 @@ +package com.leetcode.easy; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class NumberOf1Bits191Test { + private NumberOf1Bits191 solution; + + @BeforeEach + void setUp() { + solution = new NumberOf1Bits191(); + } + + @Test + void testHammingWeight_Example1() { + int n = 11; // Binary representation: 1011 + int expected = 3; + int result = solution.hammingWeight(n); + assertEquals(expected, result); + } + + @Test + void testHammingWeight_Example2() { + int n = 128; // Binary representation: 10000000 + int expected = 1; + int result = solution.hammingWeight(n); + assertEquals(expected, result); + } + + @Test + void testHammingWeight_Example3() { + int n = 2147483645; // Binary representation: 1111111111111111111111111111101 + int expected = 30; + int result = solution.hammingWeight(n); + assertEquals(expected, result); + } +}