java - Mean of two ints (or longs) without overflow, truncating towards 0 -


i'd way calculate (x + y)/2 2 integers x, y in java. naive way suffers issues if x+y > integer.max_value, or < integer.min_value.

guava intmath uses technique:

  public static int mean(int x, int y) {     // efficient method computing arithmetic mean.     // alternative (x + y) / 2 fails large values.     // alternative (x + y) >>> 1 fails negative values.     return (x & y) + ((x ^ y) >> 1);   } 

... rounds towards negative infinity, meaning routine doesn't agree naive way values {-1, -2} (giving -2, rather -1).

is there corresponding routine truncates towards 0?

"just use long" not answer i'm looking for, since want method works long inputs too. biginteger not answer i'm looking for. don't want solution branches.

you need add 1 result if lowest bits different (so result not exact , need round), , sign bit in result set (the result negative, want change round down round up).

so following should (untested):

public static int mean(int x, int y) {     int xor = x ^ y;     int roundeddown = (x & y) + (xor >> 1);     return roundeddown + (1 & xor & (roundeddown >>> 31)); } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -