1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024…
Di atas itu adalah barisan bilangan yang berada dalam bentuk 2n, dimana n = 0, 1, 2, 3.. ; n ε bilangan cacah.
Dan dibawah ini adalah method static untuk memeriksa apakah sebuah bilangan (long) merupakan bilangan 2n :
public static boolean isPowerOfTwo(long number) throws ArithmeticException{
if (number < 1) throw new ArithmeticException("number must be greater than 0");
return (number & (number - 1)) == 0;
}
to include 0, you could use
return (!(number & (number – 1)) && number);
nice blog though.
Comment by Henry Warren — July 28, 2009 @ 1:22 pm
Hi Mr. Warren…
I can’t believe you comment in my blog. I wrote this article based on your book “Hacker’s Delight”…
Thanks for the comment. I will soon update the post
Comment by hjaya — July 28, 2009 @ 1:58 pm