/**
* 功能:实现整数的乘法、减法和除法运算。只允许使用加号。
*/
//减法
public static int minus(int a,int b){
return a+negate(b);
}
//取反
/**
* 思路:对正数k的取反,只需要将-1连续加k次;对负数k的取反,只需要将1连续加k次。
* @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;
}
//乘法
/**
* 思路:a乘以b,即为a连续加b次。
* @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;
}
//取绝对值
/**
* 思路:即对负数取反。
* @param a
* @return
*/
public static int abs(int a){
if(a<0)
return negate(a);
else
return a;
}
//除法
/**
* 思路:利用等式a=xb,将b与其自身连加直至得到a,就能算出x的值。x的值为b连加的次数。
* 注意:若a不能被b整除,对于整数除法,即对结果向下取舍。
* @param a
* @param b
* @return
* @throws java.lang.ArithmeticException
*/
public static int divide(int a,int b) throws java.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;
else
return negate(x);
}