|
9 | 9 | */
|
10 | 10 | public class Addition {
|
11 | 11 |
|
| 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 | + |
12 | 61 | /**
|
13 | 62 | * Best method.
|
14 | 63 | * <p/>
|
@@ -48,6 +97,24 @@ public static int add1_V1(int n) {
|
48 | 97 | }
|
49 | 98 |
|
50 | 99 | 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("------"); |
51 | 118 | System.out.println(add1_V1(0));
|
52 | 119 | System.out.println(add1_V1(1));
|
53 | 120 | System.out.println(add1_V1(2));
|
|
0 commit comments