File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-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: 6/5/15
8
+ * @time: 3:50 PM
9
+ */
10
+ public class FlippingBits {
11
+
12
+ /**
13
+ * Returns the number by flipping/inverting its bits using
14
+ * XOR operation with 1......11 (size of int i.e, 32 1's).
15
+ *
16
+ * @param n
17
+ * @return
18
+ */
19
+ public static int getNumberByFlippingBits (int n ) {
20
+ return n ^ 0xffffffff ; // equivalent to 11....1 (32 times) in binary
21
+ }
22
+
23
+ /**
24
+ * Returns the number by flipping/inverting its bits using
25
+ * the NOT operator.
26
+ *
27
+ * @param n
28
+ * @return
29
+ */
30
+ public static int getNumberByFlippingBits_V1 (int n ) {
31
+ return ~n ;
32
+ }
33
+
34
+ public static void main (String a []) {
35
+ System .out .println (getNumberByFlippingBits (5 ));
36
+ System .out .println (getNumberByFlippingBits_V1 (5 ));
37
+ }
38
+ }
39
+
40
+ /**
41
+ * EXPLANATION:
42
+ *
43
+ * For input: 5
44
+ *
45
+ * Binary: 000.....101
46
+ * Inverted: 111.....010 (which is the 2's compliment of -6)
47
+ *
48
+ * Therefore, result is -6.
49
+ */
You can’t perform that action at this time.
0 commit comments