-2

I'm having this task, where I need to find average of 2 ints. Here is my code:

public class AverageNumber {
  public int average(int a, int b) {
    if (a == Integer.MIN_VALUE && b == Integer.MIN_VALUE) {
      return Integer.MIN_VALUE;
    } else if (a < 0 || b < 0) {
      return (a + b)/2;
    } 
    return (a+b)>>>1;
  }
}`

I fail on this test :

Input: -2147483648, -2
Expected: -1073741825
Actual: "1073741823"

I need some help working with numbers which go out of a range = Integer.MIN_VALUE. And I cannot use long type.

Mat
  • 202,337
  • 40
  • 393
  • 406
Max Shpak
  • 1
  • 1
  • When your data (and computations that depend on it) cannot fit in the storage afforded to you (which is the case here), you need to write or use one of the (many freely available) "big number" libraries. Given your statement of _I cannot use long type_, I expect you're in a class where you are expected to form your own limited big number function for this. Stack overflow is not going to write your code for you, but if you attempt to write your own and run into trouble, you might get help after posting what code and efforts you've taken to solve the issue on your own. – mah Mar 06 '16 at 18:46
  • 1
    Is this homework -- and you can only use `int`s for the calculations? – Mick Mnemonic Mar 06 '16 at 18:47
  • Actualy, given the limited scope of what you're trying to do here, no complicated library is necessary. While the normal way we think of performing an average is to add two values together and divide the result by 2, that doesn't work because you cannot safely add the two inputs. Without revealing too much, you can rewrite the formula such that you never have to add two values that will overflow the int. – mah Mar 06 '16 at 18:51

1 Answers1

0

Sounds like homework :-) it's more like a math question than a programming question.

Calculate the difference between the two and add half of the difference to the "smaller" number. You have to be a bit more elaborate to account for negative numbers but this way you won't "overflow" an int.

ssimm
  • 1,908
  • 3
  • 16
  • 36