7.4

Topic 7.4 Write methods to implement the multiply, subtract, and divide operations for integers. Use only the add operator.

First ask is this for int? If no, it is not easy to multiply float or double.

1)  减法:Just do a+(-b). 因为不能用-1乘以b,所以只好写一个把b变成负的方法。用加法,从0一个一个加-1,直到从a一个一个加-1=0为止

2)  乘法:a*b=add a to itself b times.

Improve: if a<b, add b a times; if a>b, add a b times, this can save some time.

3)  除法:b can’t be zero. a might not be evenly divisible by b, that is OK, because Integer division, is the floor of result.

public class c7_4 {
	public static int negate(int a) {//这个变负的办法很神奇
		int neg = 0;
		int d = a < 0 ? 1 : -1;
		while (a != 0) {
			neg += d;
			a += d;
		}
	    return neg;
	}
	
	public static int minus(int a, int b) {
		return a + negate(b);
	}
	
	/* Return absolute value */
	public static int abs(int a) {
		if (a < 0) {
			return negate(a);
		}
		else return a;
	}

	/* Multiply a by b by adding a to itself b times */
	public static int multiply(int a, int b) {
		if (a < b) {
			return multiply(b, a); // algo is faster if b < a
		}
		int sum = 0;
		for (int i = abs(b); i > 0; i--) {
			sum += a;
		}
		if (b < 0) {
			sum = negate(sum);
		}
		return sum;
	}
	
	public static int divide(int a, int b) throws java.lang.ArithmeticException {
		if (b == 0) {
			throw new java.lang.ArithmeticException("ERROR: Divide by zero.");
		}
		int absa = abs(a);
		int absb = abs(b);

		int product = 0;
		int x = 0;
		
		while (product + absb <= absa) { /* don't go past a */
			product += absb;
			x++;
		}
		
		if ((a < 0 && b < 0) || (a > 0 && b > 0)) {
			return x;
		} else {
			return negate(x);
		}
	}
		
	public static void main(String[] args) {
		System.out.println(negate(5));
		System.out.println(minus(7,5));
		System.out.println(multiply(7,5));
		System.out.println(divide(7,5));
	}
}
//结果
-5
2
35
1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值