Re:Fast midpoint between two integers without overflow
by DenisM on Wednesday December 07, 2022 @05:35PM
(#33901331)
Can you provide an example of a solution that someone without prior exposure could come up under 30 minutes? I'm having a hard time coming up with something that is not a monstrocity full of if s.
[ Parent
| on HN ]
Re:Fast midpoint between two integers without overflow
by ErikCorry on Wednesday December 07, 2022 @05:42PM
(#33901416)
Perhaps the bar is not as high as you think. Coming up with a solution that has lots of ifs in will still put you at the high end of the interview distribution. Discussing intelligently with the interviewer why it's not great and how it can be improved is a lot better than not coming up with an answer at all.
Re:Fast midpoint between two integers without overflow
by mojuba on Wednesday December 07, 2022 @08:20PM
(#33902858)
One of the solutions I came up with back in the day, without googling was this:
int avg(int a, int b) {
if ((a < 0) != (b < 0)) // not the same sign?
return (a + b) / 2;
else
return a + (b - a) / 2;
}
Re:Fast midpoint between two integers without overflow
by DenisM on Thursday December 08, 2022 @02:09AM
(#33905108)
It’s tricky.
This will round (-2,-1) to -2, i.e. away from zero. For comparison, if we perform the canonical (a+b)/2 instead it will round to -1, i.e. towards zero.
Now, the problem statement does not tell us how to round, so you’re technically correct, but the inconsistency bothers me.
Re:Fast midpoint between two integers without overflow
by baobabKoodaa on Wednesday December 07, 2022 @06:58PM
(#33902162)
min + (max - min) / 2
Edit: never mind, this can overflow too
Re:Fast midpoint between two integers without overflow
by stephencanon on Wednesday December 07, 2022 @08:37PM
(#33902975)
Fortunately the cases where this might overflow (a and b have opposite sign) are precisely the cases where the naive (a+b)/2 is guaranteed to work. So put them together to get a suboptimal but perfectly fine solution.