The pits encountered when averaging two numbers, adding and dividing by 2 will cause bugs

        The pits encountered when averaging two numbers, adding and dividing by 2 will cause bugs,

int mid = (low + high) / 2;

        That is to say, the above code is buggy. If the sum of low and high is greater than Integer.MAX_VALUE (2 31 -1 in Java ), the calculation will overflow, making it a negative number, and the result of dividing by 2 is of course still Is a negative number.

       

Correct the bug-free version

        Common in all situations

int mid = low + ((high - low) / 2);

       

Another show operation

        Java has a >>>unsigned right shift can be achieved by averaging

int mid1 = (high+low)>>>1;

        Note : You can only calculate the sum that is positive, because your sum is negative, so the average is also negative, but the unsigned right shift is to directly add 0 to the left, and your sign bit is gone, so the calculation must be wrong.

       

Java test code

public class Main
{
    
    
	public static void main(String[] args) {
    
    
		System.out.println("Hello World");
		int low,high,mid;
        low = -1234;
        high = 3456;
        mid = low+(high-low)/2; 
        System.out.println(mid);
        int mid1 = (high+low)>>>1;
        System.out.println(mid1);
	}
}

        Output

Hello World
1111
1111

        You can test it yourself, as long as the sum of the two is positive, the result of unsigned right shift is correct (even if the overflow is correct), and the negative number is wrong.

       

And overflow condition code

public class Main
{
    
    
	public static void main(String[] args) {
    
    
		System.out.println("Hello World");
		int low,high,mid;
        low = 2147483645;
        high = 2147483647;
        mid = low+(high-low)/2;
        System.out.println(mid);
        int mid1 = (high+low)>>>1;
        System.out.println(mid1);
	}
}

        Output

Hello World
2147483646
2147483646

Guess you like

Origin blog.csdn.net/qq_43657442/article/details/109332918
Recommended