Created
August 4, 2014 07:35
-
-
Save WOLOHAHA/f4a5a7734bf123deadbe to your computer and use it in GitHub Desktop.
Write methods to implement the multiply, subtract and divide operations for integers. Use only the add operator.
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
package POJ; | |
import java.util.ArrayList; | |
public class Main{ | |
/** | |
* | |
* 7.4 Write methods to implement the multiply, subtract and divide operations for integers. Use only the add operator. | |
* | |
*/ | |
public static void main(String[] args) { | |
Main so = new Main(); | |
int subtraction = so.divide(-99, -40); | |
System.out.println("subtraction=" + subtraction); | |
} | |
public int subtraction(int a, int b) { | |
return a + negate(b); | |
} | |
private int negate(int a) { | |
// TODO Auto-generated method stub | |
int neg = 0; | |
int b = (a < 0) ? 1 : -1; | |
while (a != 0) { | |
a += b; | |
neg += b; | |
} | |
return neg; | |
} | |
public int multiply(int a, int b) { | |
if (a < b) { | |
// algorithm is faster if b<a | |
return multiply(b, a); | |
} | |
int sum = 0; | |
for (int i = abs(b); i > 0; i--) { | |
sum += a; | |
} | |
if (b < 0) | |
sum = negate(sum); | |
return sum; | |
} | |
private int abs(int b) { | |
// TODO Auto-generated method stub | |
if (b < 0) | |
return negate(b); | |
else | |
return b; | |
} | |
public int divide(int a, int b) { | |
if (b == 0) | |
throw new java.lang.ArithmeticException(); | |
int absa = abs(a); | |
int absb = abs(b); | |
int product = 0; | |
int x = 0; | |
while (absb + product <= absa) { | |
product += absb; | |
x++; | |
} | |
if ((a > 0 && b > 0) || (a < 0 && b < 0)) | |
return x; | |
else | |
return negate(x); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment