>>> and >> are bitwise operators, only valid for integral types (not for floating-point types).
When the integer type (low+high) >>1 can replace (Low+high)/2.
>>> is the unsigned right-shift operator. If Low+high is a positive integer, these three operations are equivalent.
Because of compiler optimizations, their efficiency should be the same (if there is no compiler optimization, the shift operation is faster).
Use >>> generally have a special purpose
As for the difference between >>> and >>, it is signed and unsigned. For example, the result of -2>>>1 is 2147483647, and -2>>1 's result is-1. (where 2147483647 is-2 of the complement right moves one after the left 0 results.) )
Here the average value is calculated using >>> replacing >>, I'm afraid because there may be a large number, these numbers alone will not exceed integer.max_value, but may be exceeded after summing, if using >> or/to calculate, Negative results are calculated as a result of overflow.
Use the following procedure to illustrate the problem:
private static void Testfun () {
int low = Integer.max_value;
int high = Integer.max_value;
System.out.println ("Low:" + low); Take a look at the numbers first
int as = (low + high) >> 1;
int div = (low + high) >> 1;
int au = (low + high) >>> 1;
System.out.println ("as:" + as); Use >> to calculate the average, and/the same.
System.out.println ("div:" + div); Use >> to calculate the average, and/the same.
System.out.println ("au:" + au); Use the average of >>> calculations.
}
Execution Result:
low:2147483647
As:-1
Div:-1
au:2147483647
Why is the mean used in Java (Low+high) >>>1 instead of (Low+high)/2 or (Low+high) >>1 to calculate the average? Fortunately, where?
Why is the mean used in Java (Low+high) >>>1 instead of (Low+high)/2 or (Low+high) >>1 to calculate the average? Fortunately, where?