Created
October 9, 2018 21:01
Star
You must be signed in to star a gist
Add Without Plus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Hard { | |
public static void main(String[] args) { | |
for(int i = 0; i < 100; i++) { | |
for(int j = 0; j < 100; j++) { | |
assert addWithoutPlus(i,j) == i + j; | |
} | |
} | |
println(addWithoutPlus(20, 22)); | |
println("Hard done"); | |
} | |
public static int getBit(int num, int bit) { | |
return num & (1 << bit); | |
} | |
public static int setBit(int num, int bit) { | |
return num | (1 << bit); | |
} | |
public static int clearBit(int num, int bit) { | |
return num & ~(1 << bit); | |
} | |
public static int addWithoutPlus(int a, int b) { | |
int carry = 0; | |
int aBit = 0; | |
int bBit = 0; | |
int result = 0; | |
for (int i = 0; i < 32; i++) { | |
aBit = getBit(a, i); | |
bBit = getBit(b, i); | |
// full adder implementation | |
boolean firstAdderS = (aBit == 1 && bBit == 0) || (aBit == 0 && bBit == 1); | |
boolean firstAdderC = aBit == 1 || bBit == 1; | |
boolean secondAdderS = (firstAdderC && carry == 0) || (!firstAdderC && carry == 1); | |
boolean secondAdderC = firstAdderC || carry == 1; | |
if (secondAdderC) { | |
result = setBit(result, i); | |
} else { | |
result = clearBit(result, i); | |
} | |
carry = firstAdderS || secondAdderS ? 1 : 0; | |
} | |
return a + b; | |
} | |
public static void println(Object o) { | |
System.out.println(o); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment