Operations
int negate(int a) {
return ~a + 1;
}
int absNew(int a) {
if (a < 0) {
return negate(a);
}
return a;
}
int sub(int a, int b) {
// a - b = a + (-1)*b
return a + negate(b);
}
int mult(int a, int b) {
// one is negative
if (b < 0 ^ a < 0) {
int sum = 0;
for (int i = 0; i < absNew(b); i++) {
sum += absNew(a);
}
// negate
return negate(sum);
}
// other wise both are negative, or both are positive
// do the same thing without negating
else {
int sum = 0;
for (int i = 0; i < absNew(b); i++) {
sum += absNew(a);
}
return sum;
}
}
int divide(int a, int b) {
if (!b) {
cout << "Cannot divide by zero" << endl;
return INT_MAX;
}
// a / b = a * 1/b or the amount of times b can fit into a
int times = 0;
int b_cpy = b;
// if either is negative, negate the final result
if (a < 0 ^ b < 0) {
a = absNew(a);
b = absNew(b);
while (absNew(a) >= 0) {
int sub_ = sub(a, b);
if (sub_ < 0) return negate(times);
else {
a -= b;
times++;
}
}
}
else {
a = absNew(a);
b = absNew(b);
while (absNew(a) >= 0) {
int sub_ = sub(a, b);
if (sub_ < 0) return times;
else {
a -= b;
times++;
}
}
}
}
int main()
{
cout << absNew(-7) << endl;
cout << absNew(100) << endl;
cout << absNew(0) << endl;
pause();
cout << negate(-7) << endl;
cout << negate(100) << endl;
cout << negate(0) << endl;
pause();
cout << sub(7, 6) << endl;
cout << sub(100, -3) << endl;
cout << sub(-400, 473) << endl;
cout << sub(-23, -3) << endl;
cout << sub(0,0) << endl;
pause();
cout << mult(7, 6) << endl;
cout << mult(100, -3) << endl;
cout << mult(-400, 473) << endl;
cout << mult(-23, -3) << endl;
cout << mult(0, 0) << endl;
pause();
cout << divide(7, 6) << endl;
cout << divide(100, -3) << endl;
cout << divide(-400, 473) << endl;
cout << divide(-23, -3) << endl;
cout << divide(0,0) << endl;
pause();
}Last updated