Reputation: 319
I'm attempting to find the integer midpoint between two integers. For example mid(2,3) would be 2, not 2.5. I had the below which works fine, but i'd like to work with numbers from MIN_VALUE to MAX_VALUE, and doing so causes overflow so completely incorrect results.
public static int mid(int x, int y){
int midpoint = (x+y)/2;
return midpoint;
}
I've now got:
public static int mid(int x, int y){
int low = Math.min(x, y);
int high = Math.max(x, y);
int midpoint = (low + high) >>> 1;
return midpoint;
}
This seems to work for values of x and y from 0 up to Integer.MAX_VALUE, however is incorrect if x is a negative number and i'm unsure why that is?
Upvotes: 2
Views: 10247
Reputation: 1138
How about this one?
public static int mid(int x, int y) {
return x/2 + y/2 + (x%2 + y%2)/2;
}
Upvotes: 4
Reputation: 187
a >>> operator fills the top bits with zero, unlike >> which extends the sign bit into the top bits.so bitwise operator >> is helpful:
public static int mid(int x, int y){
int midpoint = (x>>1) + (y>>1);
if((x&0b1)/0b1==1&&(y&0b1)/0b1==1){
midpoint++;
}
return midpoint;
}
for example: 1111 1110(decimal -2) + 0000 0001(decimal 1) = 1111 1111(decimal -1)
1111 1111(decimal -1)>>1 = 1111 1111(decimal -1)
while
1111 1111(decimal -1)>>>1 = 0111 1111(decimal 127)
(java type 'Integer' is 4 bytes,here just to illustrate )
I think this may be useful to understand the result;
Upvotes: 1
Reputation: 496
What about something like this?
public static int mid(int x, int y){
long difference = (long)y - x;
long adDiff = difference/2;
return (long) (x + adDiff);
}
You have to cast it to a long so that in the instance where y-x
is greater then MAX_VALUE you don't overflow.
Upvotes: 1
Reputation: 3409
You can work around with convert to long and back:
public static int mid(int x, int y) {
return (int) (((long)x + y) / 2);
}
Upvotes: 2