A power of 2?
- O(log n) · Easy
- Free
- Python
- JavaScript
- loops
- operations
- booleans
Problem
Write a function that takes a whole number and returns true if it is a power of 2 (1, 2, 4, 8, 16, 32...) and false if it is not.
The 1 does count: it is 2 to the 0. Zero and the negatives are not powers of 2, so with them you return false.
An idea: divide by 2 with a while as long as the number is even. If you end up with 1, it was a power of 2.
Examples
1 → true
2 → true
8 → true
6 → false
3 → false
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def is_power_of_two(n):
passJavaScript
function isPowerOfTwo(n) {
}Solve this challenge
It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.