How can I multiply and divide using only bit shifting and adding?

后端 未结 14 1769
清歌不尽
清歌不尽 2020-11-22 15:09

How can I multiply and divide using only bit shifting and adding?

14条回答
  •  野性不改
    2020-11-22 15:36

    Taken from here.

    This is only for division:

    int add(int a, int b) {
            int partialSum, carry;
            do {
                partialSum = a ^ b;
                carry = (a & b) << 1;
                a = partialSum;
                b = carry;
            } while (carry != 0);
            return partialSum;
    }
    
    int subtract(int a, int b) {
        return add(a, add(~b, 1));
    }
    
    int division(int dividend, int divisor) {
            boolean negative = false;
            if ((dividend & (1 << 31)) == (1 << 31)) { // Check for signed bit
                negative = !negative;
                dividend = add(~dividend, 1);  // Negation
            }
            if ((divisor & (1 << 31)) == (1 << 31)) {
                negative = !negative;
                divisor = add(~divisor, 1);  // Negation
            }
            int quotient = 0;
            long r;
            for (int i = 30; i >= 0; i = subtract(i, 1)) {
                r = (divisor << i);
               // Left shift divisor until it's smaller than dividend
                if (r < Integer.MAX_VALUE && r >= 0) { // Avoid cases where comparison between long and int doesn't make sense
                    if (r <= dividend) { 
                        quotient |= (1 << i);    
                        dividend = subtract(dividend, (int) r);
                    }
                }
            }
            if (negative) {
                quotient = add(~quotient, 1);
            }
            return quotient;
    }
    

提交回复
热议问题