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

Commit 7c204e9

Browse files
author
Ram swaroop
committed
addition without using arithmetic operators done
1 parent 2f627ca commit 7c204e9

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/me/ramswaroop/bits/Addition.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,55 @@
99
*/
1010
public class Addition {
1111

12+
/**
13+
* Better solution.
14+
* <p/>
15+
* Adds two numbers without using any
16+
* arithmetic operators.
17+
*
18+
* @param x
19+
* @param y
20+
* @return sum of {@param x} and {@param y}
21+
*/
22+
public static int add(int x, int y) {
23+
int carry;
24+
while (y != 0) {
25+
carry = x & y;
26+
x = x ^ y;
27+
y = carry << 1;
28+
}
29+
return x;
30+
}
31+
32+
/**
33+
* Naive approach.
34+
* <p/>
35+
* Adds two numbers without using any
36+
* arithmetic operators.
37+
*
38+
* @param x
39+
* @param y
40+
* @return sum of {@param x} and {@param y}
41+
*/
42+
public static int add_V1(int x, int y) {
43+
int carry = 0, sum = 0, c = 0, xLSB, yLSB;
44+
while (c < 32) {
45+
xLSB = x & 1;
46+
yLSB = y & 1;
47+
sum |= (xLSB ^ yLSB ^ carry) << c;
48+
if ((xLSB & yLSB) == 1 || (xLSB & carry) == 1 || (yLSB & carry) == 1) {
49+
carry = 1;
50+
} else {
51+
carry = 0;
52+
}
53+
x >>= 1;
54+
y >>= 1;
55+
c++;
56+
}
57+
return sum;
58+
}
59+
60+
1261
/**
1362
* Best method.
1463
* <p/>
@@ -48,6 +97,24 @@ public static int add1_V1(int n) {
4897
}
4998

5099
public static void main(String a[]) {
100+
System.out.println(add(0, 0)); //0
101+
System.out.println(add(12, 12)); //24
102+
System.out.println(add(12, 5)); //17
103+
System.out.println(add(3, 5)); //8
104+
System.out.println(add(8, 5)); //13
105+
System.out.println(add(13, 256)); // 269
106+
System.out.println(add(456, 982348234)); // 982348690
107+
System.out.println(add(1, 0xffffffff)); // 0
108+
System.out.println("------");
109+
System.out.println(add_V1(0, 0)); //0
110+
System.out.println(add_V1(12, 12)); //24
111+
System.out.println(add_V1(12, 5)); //17
112+
System.out.println(add_V1(3, 5)); //8
113+
System.out.println(add_V1(8, 5)); //13
114+
System.out.println(add_V1(13, 256)); // 269
115+
System.out.println(add_V1(456, 982348234)); // 982348690
116+
System.out.println(add_V1(1, 0xffffffff)); // 0
117+
System.out.println("------");
51118
System.out.println(add1_V1(0));
52119
System.out.println(add1_V1(1));
53120
System.out.println(add1_V1(2));

0 commit comments

Comments
 (0)