Member-only story
Leetcode: Power of Two Python Solution
The Question
Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
We are given a couple of examples to demonstrate how the output should look like:
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Output: false
This is a leetcode easy question, hence it is expected that you should easily find an optimal solution for this problem. We are going to look at two different approaches for this problem.
Approach 1
A number that is a power two has a modulus zero when divided by 2. Hence we can use this fact to check whether numbers are powers of two. The time complexity using this method will be 0(log n) and a space complexity of 0(n)
Here is the solution in code: