7.4

来源:互联网 发布:数据库导入excle 编辑:程序博客网 时间:2024/05/21 09:25

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));}}
//结果-52351


原创粉丝点击