Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if number is in the binary sequence 1 2 4 8 16 32 64 etc [duplicate]

Tags:

c#

.net

math

binary

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?

like image 509
Shimmy Weitzhandler Avatar asked Feb 13 '12 11:02

Shimmy Weitzhandler


1 Answers

The following expression should be true if i is in your sequence.

(i & (i-1)) == 0)

http://rextester.com/JRH41036

like image 135
Sam Greenhalgh Avatar answered Sep 28 '22 06:09

Sam Greenhalgh