Yet Another No-Solve Prevention Problem!!
InterviewTime limit2sMemory limit512 MB
For each of Q queries, decide whether the given number a is a power of two, printing 1 for yes and 0 for no.
- Level
Easy3 of 10
- Topics
- Bit manipulation, Math, Implementation, Brute force
- Solved
- No attempts yet
Problem
You must process queries. Each query is the following.
Can the number be written as a power of two?
Input
The first line gives . ()
The second line through the -th line give . Each is a natural number with .
Output
For each query, print 1 if the answer is Yes, and 0 otherwise.
Hint
Suppose some number can be written as a power of two. Then for some integer . Usually, checking each bit and counting the number of set bits is also a good approach. This performs at most about 32 operations, so with queries in total the time complexity is .
But is there a better way? Write () in binary, and split into the cases where is odd and where is even.
...01
How is written then?
...11
So gives 1. What if is even?
...10...0
This is how it is written. How is written then? First flip the bits.
...01...1
Adding 1 to this is the two's complement representation. So is written as
...10...0
Therefore is related to the lowest set bit of . Here is an example. When , what is the value of ?
so .
Now observe what property has when it is written as .
So if , then is a power of two; otherwise it is not.