publicstaticintadd(int a, int b) { intsum= a; while(b != 0) { sum = a ^ b; //无进位相加信息-> sum b = (a & b) << 1; //进位信息 -> b->b' a = sum; //a -> a' 无进位相加信息 } return sum; }
publicstaticintminus(int a, int b) { return add(a,negNum(b)); }
乘法实现
同样也是给出两个数a和b,和小学算术题一样,需要用a每个位乘以b的每个位,然后再加起来
1 2 3 4 5 6 7 8 9 10 11 12
// 乘法(支持正数负数) publicstaticintmulti(int a, int b) { intres=0; while (b != 0) { if ((b & 1) != 0){ res = add(res, a); } a <<=1; b >>>= 1; } return res; }
// 除法 publicstaticintdiv(int a, int b) { intx= isNeg(a) ? negNum(a) : a; inty= isNeg(b) ? negNum(b) : b; intres=0; // x / y for (inti=30; i>= 0; i = minus(i,1)) { if ((x >> i) >= y) { res |= (1 << i); x = minus(x, y << i); } } return isNeg(a) != isNeg(b) ? negNum(res) : res; }
// 如果是系统最小值,需要进行判断 publicstaticintdivide(int a, int b) { if (a == Integer.MIN_VALUE && b == Integer.MIN_VALUE) { return1; }elseif (b == Integer.MIN_VALUE){ return0; }elseif (a == Integer.MIN_VALUE){ if (b== negNum(1)){ return Integer.MAX_VALUE; }else { /* * a / b * (a + 1) / b == c * a - (b * c) = d * d / b = e * c+ e*/