Learner Level
Implement the method isPowerOfTwo that checks whether an integer is a power of two.
A number is a power of two if it can be written as 2^k for some whole number k.
The task is designed to test careful handling of edge cases, not only the most common input.
- Return
falsefor zero and negative numbers. 1is a power of two.- You may use division or bit operations.
Example 1
Input
n (int) =
1Returns (boolean)
trueExample 2
Input
n (int) =
16Returns (boolean)
trueExample 3
Input
n (int) =
18Returns (boolean)
falseExample 4
Input
n (int) =
0Returns (boolean)
falseRepeatedly divide by two while the number is even. The final value must be one.
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run