Skip to content

Instantly share code, notes, and snippets.

@xetys
Created October 9, 2018 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xetys/837365ab3796fcdf51a090a5c74188b8 to your computer and use it in GitHub Desktop.
Save xetys/837365ab3796fcdf51a090a5c74188b8 to your computer and use it in GitHub Desktop.
Add Without Plus
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