Divide Two Numbers Without Symbol And Also Minus And Multiply

来源:互联网 发布:什么是网络设计 编辑:程序博客网 时间:2024/05/01 06:25
    public int divide(int dividend, int divisor) {        if(dividend == 0) return 0;        if(divisor == 0) return (dividend > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;                boolean flag = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0);                long a = Math.abs((long)dividend);        long b = Math.abs((long)divisor);         //if b is less than a, then move the highest digit of b to maybe the same with a        //if a is less than b, then moveTimes will be 0        int moveTimes = 0;        for(; a >= (b << 1); moveTimes++) {            b <<= 1;        }                int result = 0;        for(; moveTimes >= 0; moveTimes--){                if(a >= b){                 a -= b;                result += (1 << moveTimes);            }            b >>= 1;        }        if(flag) return result;        else return -result;    }            //minus two numbers without minuspublic int minus(int a, int b) {return a + help(b);}public int help(int a) {int result = 0;int tmp = (a < 0) ? 1 : -1;while(a != 0) {result += tmp;a += tmp;}return result;}//multiply two numbers without multiplypublic int multiply(int a, int b) {if(a < b) return multiply(b, a);int result = 0;for(int i = abs(b); i > 0; i--) {result += a;}if(b < 0) return help(result);return result;}public int abs(int a) {if(a < 0) return help(a);return a;}

原创粉丝点击