Possible Duplicate:
How to check if a number is a power of 2
I want to determine if a number is in
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
...
I tried this:
public static void Main(string[] args)
{
int result = 1;
for (int i = 0; i < 15; i++)
{
//Console.WriteLine(result);
Console.WriteLine(result % 2);
result *= 2;
}
}
As you can see it returns
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
...
How should I efficiently make the above print to be 0
for all of them including 1?
The following expression should be true if i
is in your sequence.
(i & (i-1)) == 0)
http://rextester.com/JRH41036
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With