Re:How many Java programmers does it take to round up to a p...
by asmosoinio on Friday November 02, 2007 @07:26AM
(#75400)
Funny thread! :)
I guess the thing here is that bit operators are not really "in you face" in Java. If you are programming in assembler, or even C, bits will be what you know. Programming at a higher level, you may not be that aware of bit functions and how to use them in real life. You should, but many are not.
The second approach by gojomo here is neat and effective and works directly at the bits instead of bloating with creating Strings and other objects for this simple task. So it's not the fault of the tool, it about the abstraction level people are thinking in.
Re:How many Java programmers does it take to round up to a p...
by tallpapab on Friday November 02, 2007 @03:04PM
(#75542)
You have an infinite loop when i < 2^30.
static int nextOne(int theInt) {
int answer = 1;
while (answer < theInt && 0 < answer) {
answer <<= 1;
}
if (answer < 1) {
throw new IllegalArgumentException("Sorry, " +
theInt + " is bigger than 2 to the power of 30 (1073741824).");
}
return answer;
}
And if we weren't being literal-minded about the original request, it might make sense to just return the exponent rather than the power-of-2 itself, and let the caller worry about overflows:
static int ceilLog2(long val) {
return BigInteger.valueOf(val-1).bitLength();
}
Of course we are ignoring negative exponents, in the integer spirit of the original question.
I guess the thing here is that bit operators are not really "in you face" in Java. If you are programming in assembler, or even C, bits will be what you know. Programming at a higher level, you may not be that aware of bit functions and how to use them in real life. You should, but many are not.
The second approach by gojomo here is neat and effective and works directly at the bits instead of bloating with creating Strings and other objects for this simple task. So it's not the fault of the tool, it about the abstraction level people are thinking in.
If I were defensively programming against unanswerable input, I'd tend towards failing fast with a single early check:
If we needed to give answers for any size integer (or at least up to 2^(2^31-1)), we could use BigInteger, whose #bitLength method is useful: And if we weren't being literal-minded about the original request, it might make sense to just return the exponent rather than the power-of-2 itself, and let the caller worry about overflows: Of course we are ignoring negative exponents, in the integer spirit of the original question.There, is it done to death yet? :)
why not just something like
def fn(n): ret=1; while ret < n: ret <<= 1; return ret
(news.yc/browsers mangle whitespace; proper formatting is left as an exercise to the reader)
Reddit is 2 and 4.
http://lispy.wordpress.com/2007/11/02/my-solution-to-the-rou...