Blind 75
Number of 1 Bits
- Problem
- LC 191
- Category
- Binary
- File
- blind75_LC191NumberOf1Bits.java
- Path
- pkg5leetcode/blind75/blind75_LC191NumberOf1Bits.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC191NumberOf1Bits.java
- Approach
- Clear lowest set bit with n &= n-1 per iteration.
- Complexity
- Time O(k) bits set, Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Number of 1 Bits | LC 1915 * APPROACH: Clear lowest set bit with n &= n-1 per iteration.6 * COMPLEXITY: Time O(k) bits set, Space O(1)7 */8public class blind75_LC191NumberOf1Bits {9 static int hammingWeight(int n) {10 int count = 0;11 while (n != 0) {12 n &= n - 1;13 count++;14 }15 return count;16 }17 18 public static void main(String[] args) {19 check(hammingWeight(11) == 3, "case1");20 check(hammingWeight(128) == 1, "case2");21 System.out.println("all tests passed");22 }23 24 static void check(boolean cond, String name) {25 if (!cond) throw new AssertionError("FAILED: " + name);26 System.out.println(" PASS " + name);27 }28}