File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ package me .ramswaroop .bits ;
2
+
3
+ /**
4
+ * Created by IntelliJ IDEA.
5
+ *
6
+ * @author: ramswaroop
7
+ * @date: 7/22/15
8
+ * @time: 12:42 PM
9
+ */
10
+ public class CountSetBitsFromMinusNtoN {
11
+
12
+ /**
13
+ * Explanation:
14
+ *
15
+ * -3: 101
16
+ * -2: 110
17
+ * -1: 111
18
+ * 0: 000
19
+ * 1: 001
20
+ * 2: 010
21
+ * 3: 110
22
+ *
23
+ * If you fold the above representation between -1 and 0, the total no. of set bits from -3 to 2
24
+ * will be equal to the total no. of bits in nos. from -3 to 2.
25
+ *
26
+ * @param n
27
+ * @return
28
+ */
29
+ public static int countSetBitsFromMinusNtoN (int n ) {
30
+ return n * 32 + CountSetBits .countSetBits ((long ) n ); // 32 because int is of 32 bits in java
31
+ }
32
+
33
+ public static void main (String a []) {
34
+ System .out .println (countSetBitsFromMinusNtoN (3 ));
35
+ System .out .println (countSetBitsFromMinusNtoN (0 ));
36
+ System .out .println (countSetBitsFromMinusNtoN (9 ));
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments