Skip to content

Commit e50a74a

Browse files
committed
add math
1 parent 75504e4 commit e50a74a

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

MathOps/src/MathOps.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,40 @@ public static double pow(double x, int y){
4040
return r;
4141
}
4242

43+
public static int divide(int dividend, int divisor){
44+
45+
if ( divisor == 0)
46+
throw new ArithmeticException("divisor is 0");
47+
48+
boolean neg_dividend = (dividend <0);
49+
boolean neg_divisor = (divisor <0);
50+
51+
if(neg_dividend)
52+
dividend = (dividend^-1)+1;
53+
if(neg_divisor)
54+
divisor = (divisor^-1)+1;
55+
56+
int result = 0;
57+
58+
while (dividend >= divisor){
59+
dividend -= divisor;
60+
result++;
61+
62+
}
63+
64+
if(neg_dividend^neg_divisor)
65+
result = (result^-1)+1;
66+
67+
return result;
68+
69+
}
70+
4371
public static void main(String[] args){
4472

4573
System.out.println("add: " + add(6, -2));
4674
System.out.println("sqrt: " + sqrt(120.0));
4775
System.out.println("pow: " + pow(2.0,-3));
76+
System.out.println("divide: " + divide(-21474,3));
77+
4878
}
4979
}

0 commit comments

Comments
 (0)