Seems like the approach you've taken is to implement the + operator yourself. And when using the + operator on negative numbers, you've implemented your own - operator.
I have to congratulate you for being able to implement these operators from scratch. Good job.
A slight bug is that your code returns incorrect result for divide(-42, 6)
I believe the source of this bug is that this code is inside the while:
if (isNeg) {
sign=!sign;
}
Put it outside the while and it seems to work (at least for my test case)
if (a < b) return 0;
else{
You can save yourself some trouble indentation by removing that else. As you return, you can keep on going without adding indentation. (Which is why I love early returns)
Your spacing is a bit off, the easiest way to fix this is to press Ctrl + Shift + F if you're using Eclipse, or Alt + Shift + F if you're using Netbeans.
For example, this line:
while(Math.abs(s)>=Math.abs(divisor)){
Would look better like this:
while (Math.abs(s) >= Math.abs(divisor)) {
quotient = add(0, -quotient);
As you're using a - sign there already, why not replace all this with -quotient?
You have three boolean values related to the positive/negative issue:
boolean isNeg = false;
boolean sign = true;
boolean bothNegative = false;
Only one would be enough:
boolean swapSign = a < 0 ^ b < 0;
This is using the boolean XOR operator (^), so this will be true if a is negative or b is negative, but not if both are negative.
int quotient = 1;
if (a < b) {
return 0;
}
You're using a < b as a special case, but that's not necessary.
int s;
That's not a readable name.
You can get rid of several unnecessary variables by directly operating on the a and b values. As they're ints, they're value-typed and therefore copied and not sent by reference, which means that you can modify them however you'd like inside your method. They can be used just like normal local variables.
The main part of your method can be simply this:
a = Math.abs(a);
b = Math.abs(b);
int result = 0;
while (a >= b) {
a = add(a, -b);
result = add(result, 1);
}
Your logic for what to return is a bit bloated:
if (bothNegative) {
return quotient;
}
else if (isNeg && !sign) {
quotient = add(0, -quotient);
}
return quotient;
This can be replaced with, by using the single swapSign variable:
if (swapSign) {
return -result;
}
else {
return result;
}
Or even simpler, using the ternary operator:
return swapSign ? -result : result;
End result:
private static int divide(int a, int b) {
boolean swapSign = a < 0 ^ b < 0;
a = Math.abs(a);
b = Math.abs(b);
int result = 0;
while (a >= b) {
a = add(a, -b);
result = add(result, 1);
}
return swapSign ? -result : result;
}