Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The above gives an incorrect result for approxSize = 1 (namely 0). The following works (for values up to 2^30, of course):

    var actualSize = Integer.MIN_VALUE >>> Integer.numberOfLeadingZeros(approxSize - 1) - 1;
Or, if you want 0 to map to 0 instead of to 1:

    var actualSize = Integer.signum(approxSize) * Integer.MIN_VALUE >>> Integer.numberOfLeadingZeros(approxSize - 1) - 1;
Of course, you could also use a variation of:

    var actualSize = Math.min(1, Math.Integer.highestOneBit(approxSize - 1) << 1);



Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: