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 false for zero and negative numbers.
  • 1 is a power of two.
  • You may use division or bit operations.

Example 1

Input
n (int) = 1
Returns (boolean) true

Example 2

Input
n (int) = 16
Returns (boolean) true

Example 3

Input
n (int) = 18
Returns (boolean) false

Example 4

Input
n (int) = 0
Returns (boolean) false

Repeatedly 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

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.