/**
* Function: The multiplication, subtraction and division of integers are realized. Only the plus sign is allowed.
*/
Subtract public static int minus (int a,int b) {return a+negate (b);} Take anti-/** * idea: The positive number of k, only need to be 1 continuous plus k times, negative k of the inverse, only need to be 1 continuous plus k times. * @param A * @return */public static int negate (int a) {int neg=0;int d=a>0?-1:1;while (a!=0) {neg+=d;a+=d;} return neg;} Multiplication/** * Idea: a multiplied by B, that is a continuous plus B times. * @param A * @param b * @return */public static int multiply (int a,int b) {if (a<b) 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;} Take the absolute value/** * idea: that is negative negation. * @param A * @return */public static int abs (int a) {if (a<0) return negate (a); else return A;} Division/** * Idea: Using the equation a=xb, the B is connected with itself until you get a, you can calculate the value of X. The value of x is the number of times B is added. * Note: If a cannot be divisible by B, for integer division, the result is a downward tradeoff. * @param A * @param b * @return * @throws java.lang.ArithmeticException */public static int divide (int a,int b) throws Jav A.lang.arithmeticexception{if (b==0) {throw new Java.lang.ArithmeticException ("Error");} int Absa=abs (a); int absb=abs (b); int product=0;int X=0;while (PRODUCT+ABSB<=ABSA) {product+=absb;x++;} if (a<0&&b<0| | a>0&&B>0) return X;elsereturn negate (x);}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9.7 Mathematics and Probability (ii)--to achieve multiplication, subtraction, and division of integers, with only a plus sign allowed