Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5f9258e

Browse files
author
Ram swaroop
committed
add 1 without + operator done
1 parent 2c9489a commit 5f9258e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/me/ramswaroop/bits/Addition.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

0 commit comments

Comments
 (0)