Power of Two
LeetCode Problem #231 (Easy)
Problem Statement
Given an integer, write a function to determine if it is a power of two.
Testcases
Problem Explanation
A number is a power of two if it can be formed by repeatedly multiplying some number of 2's.
16 is a power of 2 since 16 = 2 * 2 * 2 * 2.
This can alternatively be written as 16 = 2^4.
We must determine whether a particular number is a power of two.
Example:
If n = 16
If n = 17
Algorithm
Iterative Approach
If the number is 0, it cannot be a power of 2.
If the number is 1, since 2 ^ 0 = 1, it is a power of 2.
Iteratively reduce the power of the number by dividing by 2.
a. If the number % 2 yields a remainder and is not 1, then it is not a power of 2.
b. If the number evenly divides 2 and yields no remainder, it is a power of 2.
Code
Last updated
Was this helpful?