LeetCode_ dividing the two

Title
given two integers, dividend dividend and divisor divisor. The dividing the two requirements without using multiplication, division, and the mod operator.
Returns the dividend divided by the divisor dividend quotient divisor get.

Example 1:
Input: dividend = 10, divisor = 3
Output: 3

Example 2:
Input: dividend = 7, divisor = -3
Output: -2

Thinking:
Thinking 1: Save to continuously cycle through the dividend by the divisor, the divisor is less than when the dividend, the number of subtraction is the supplier. But when a large dividend, the divisor is relatively small (dividend = 2 ^ 31, divisor = 1) is bound to consume a lot of time, eventually leading to a timeout.
Very efficient bit computing, left one by 2, that right is divided by 2, we can put a first dividend divided by 2 ^ n, n bits that is the right move, since the number of signed number: Ideas 2 , n is 31 at first, and then decreasing gradually approaching the divisor n, when the dividend / 2 ^ n> = divisor , the dividend - 2 ^ * divisor when the divisor is less than n, then n ^ 2 is the provider, if the dividend - divisor * when the divisor n is greater than 2 ^, cycle once again by the above method.

java:
class Solution {
	public static void main(String[] args) {
		System.out.println(divide(10,3));
		System.out.println(1<<3);
	}
	public static int divide(int dividend, int divisor) {
        boolean Symbol = (dividend ^ divisor) >= 0;    //如果大于0 两数符号相同
        long _dividend = (Math.abs((long)dividend));
        long _divisor = (Math.abs((long)divisor));
        
        if(dividend == Integer.MIN_VALUE && divisor == -1){
            return Integer.MAX_VALUE;
        }    //int最小值为2^31,除以-1就是2^31,但int最大取值2^31-1,会导致溢出
        int result = 0;
        for(int i = 31;i>=0;i--){
            if((_dividend>>i)>=_divisor){
                result = result + (1<<i);
                _dividend = _dividend - (_divisor<<i);
            }
        }
        if(Symbol == true){
            return result;
        }
        else
            return -result;
    }
}

pit:

1.long _dividend = ((long) Math.abs (dividend)); At first the long written on the outside Math lead when the absolute value has overflowed, should be changed to long _dividend = (Math.abs ((long) dividend));

Guess you like

Origin blog.csdn.net/w819104246/article/details/92390817