shift operator
<< : Bitwise left shift operator. The left operand is shifted to the left by the number of bits specified by the right operand. num << 1, the result is equivalent to multiplying num by 2
>> : Bitwise right shift operator. Shifts the left operand to the right by the number of bits specified by the right operand. num >> 1, the result is equivalent to dividing num by 2
In the java.util.ArrayList.grow(int) method,
int newCapacity = oldCapacity + (oldCapacity >> 1);
ArrayList is expanded by 1.5 times the original size
>>> : unsigned right shift, ignoring the sign bit, and padded with 0
Specific application: java.util.Arrays.binarySearch(long[], long) in JDK's binary search code implementation
public static int binarySearch(long[] a, long key) {
return binarySearch0(a, 0, a.length, key);
}
// Like public version, but without range checks.
private static int binarySearch0(long[] a, int fromIndex, int toIndex,
long key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
//无符号右移
int mid = (low + high) >>> 1;//equal mid=low +(high-low)/2;
long midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
XOR ^ operator
The XOR operation rule is: If the binary bits of the two operands are the same, the result is 0, and if they are different, the result is 1.
If the values of a and b are the same, the XOR result is 0. If the two values of a and b are not the same, the XOR result is 1.
All numbers in a sorted array appear 2 times, and one of the numbers only appears 1 time, find this number?
public static int getonenum(int a[], int size) {
int result = 0;
for (int i = 0; i < size; i++) {
result ^= a[i];
}
return result;
}
swap the values of two numbers
ch[i] ^= ch[len - 1 - i];
ch[len - 1 - i] ^= ch[i];
ch[i] ^= ch[len - 1 - i];