Skip to content

Instantly share code, notes, and snippets.

@xetys xetys/Hard.java
Created Oct 9, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.