File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-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/10/15
8
+ * @time: 12:55 PM
9
+ */
10
+ public class Addition {
11
+
12
+ /**
13
+ * Idea is to flip all the bits of {@param n} till
14
+ * rightmost 0 bit in {@param n}.
15
+ *
16
+ * @param n
17
+ * @return
18
+ */
19
+ public static int add1 (int n ) {
20
+ int mask = 1 ;
21
+ // flip all bits in n until rightmost 0 bit
22
+ while ((n & mask ) != 0 ) {
23
+ n ^= mask ;
24
+ mask <<= 1 ;
25
+ }
26
+ // flip the rightmost 0 bit
27
+ return n ^ mask ;
28
+ }
29
+
30
+ public static void main (String a []) {
31
+ System .out .println (add1 (0 ));
32
+ System .out .println (add1 (1 ));
33
+ System .out .println (add1 (2 ));
34
+ System .out .println (add1 (3 ));
35
+ System .out .println (add1 (4 ));
36
+ System .out .println (add1 (5 ));
37
+ System .out .println (add1 (7 ));
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments