M
Matt
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.
No loops allowed.
Matt said:Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.
Matt said:Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.
isPow2 = x && !( (x-1) & x );
Joona I Palaste said:((((x&&!(x&(x-!!x)))+x)-x)^x)^x
What do I win?
Matt said:Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.
In said:We're not here to do your homework for you.
In said:i know this works because i just tested it .. but help me understand
the algoritm please ..
Aishwarya said:i know this works because i just tested it .. but help me understand
the algoritm please ..
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.
Ed said:if (!(x%2)) {
puts("x is a power of 2");
}
Are you implying that 42 is a power of 2 and 43 is not?
BTW: It's a three-liner and no C expression at all. ;-)
Jirka
Joona I Palaste said:((((x&&!(x&(x-!!x)))+x)-x)^x)^x
What do I win?
Eric Sosman said:true_or_false = a_number > 0;
(For example, 3.14159 ~= 2 ** 1.65149.)
^^^^^^^^^^^^Ed said:if (!(x%2)) {
puts("x is a power of 2");
}
Now, !!x is an obfuscated way of writing 1, when you know that x cannot
be zero (it was already tested)
jacob navia said:Algorithm:
If x is a power of two, it doesn't have any bits in common with x-1, since it
consists of a single bit on. Any positive power of two is a single bit, using
binary integer representation.
This means that we test if x-1 and x doesn't share bits with the and operator.
Of course, if x is zero (not a power of two) this doesn't hold, so we add an
explicit test for zero with xx && expression.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.