File tree 2 files changed +37
-0
lines changed
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -48,4 +48,32 @@ public long countSetBits(long num) {
48
48
}
49
49
return cnt ;
50
50
}
51
+
52
+ /**
53
+ * This approach takes O(1) running time to count the set bits, but requires a pre-processing.
54
+ *
55
+ * So, we divide our 32-bit input into 8-bit chunks, with four chunks. We have 8 bits in each chunk.
56
+ *
57
+ * Then the range is from 0-255 (0 to 2^7).
58
+ * So, we may need to count set bits from 0 to 255 in individual chunks.
59
+ *
60
+ * @param num takes a long number
61
+ * @return the count of set bits in the binary equivalent
62
+ */
63
+ public int lookupApproach (int num ) {
64
+ int [] table = new int [256 ];
65
+ table [0 ] = 0 ;
66
+
67
+ for (int i = 1 ; i < 256 ; i ++) {
68
+ table [i ] = (i & 1 ) + table [i >> 1 ]; // i >> 1 equals to i/2
69
+ }
70
+
71
+ int res = 0 ;
72
+ for (int i = 0 ; i < 4 ; i ++) {
73
+ res += table [num & 0xff ];
74
+ num >>= 8 ;
75
+ }
76
+
77
+ return res ;
78
+ }
51
79
}
Original file line number Diff line number Diff line change @@ -14,4 +14,13 @@ void testSetBits() {
14
14
assertEquals (5 , csb .countSetBits (10000 ));
15
15
assertEquals (5 , csb .countSetBits (31 ));
16
16
}
17
+
18
+ @ Test
19
+ void testSetBitsLookupApproach () {
20
+ CountSetBits csb = new CountSetBits ();
21
+ assertEquals (1L , csb .lookupApproach (16 ));
22
+ assertEquals (4 , csb .lookupApproach (15 ));
23
+ assertEquals (5 , csb .lookupApproach (10000 ));
24
+ assertEquals (5 , csb .lookupApproach (31 ));
25
+ }
17
26
}
You can’t perform that action at this time.
0 commit comments