Question
Solution
Main idea of the title: Given two numbers, it is required that multiplication, division and redundancy operations should not be used to derive their quotients.
Ideas: Let's talk about the method of using displacement to realize it.
7/3 = 2, 7 is dividend, 3 is divisor Let's move the divisor to the left, assuming that it moves n times and moves to the nearest dividend, when the divisor = dividend-divisor, part of quotient is 2^n. If the dividend > the dividend, the loop continues When the divisor moves to the left and moves m times, it moves to the nearest dividend, where the divisor = dividend-divisor and the quotient part is 2^m. The final quotient is 2^n+2^m +...
Java implementation:
Method 1: If divisions can be used, one step will do.
public int divide2(int dividend, int divisor) { // overflows if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE; // Given two numbers, finding their quotients requires that multiplication, division and redundancy operations should not be used. return dividend / divisor; }
Law 2: The following is achieved by subtraction, execution timeout
public int divide2(int dividend, int divisor) { // overflows if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE; int ans = 0; boolean negative = !((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)); dividend = Math.abs(dividend); divisor = Math.abs(divisor); dividend -= divisor; while (dividend >= 0) { ans++; dividend -= divisor; } return negative ? -ans : ans; }
Method 3: Implemented by Shift
public int divide(int dividend, int divisor) { // Prevent overflow if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE; // Symbols to get the final result int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; long dvd = Math.abs((long) dividend); long dvs = Math.abs((long) divisor); int ans = 0; while (dvd >= dvs) { long tmp = dvs, multiple = 1; while (dvd >= (tmp << 1)) { tmp <<= 1; multiple <<= 1; } dvd -= tmp; ans += multiple; } return sign == 1 ? ans : -ans; }