Problem:
Given an integer number, decide if it's a power of 2. Return true if yes, otherwise return false.
Analysis:
Can the number be negative?
>> Should not be. Since a power of any number can only be positive. Hence, let me assume non-negative numbers only in this problem.
Solution 1:
Runs in constant time and makes use of bit operations.
Solution 2:
Shifts the bits and counts the number of 1's.
Solution 3:
Uses arithmetic operation only. This is similar to Solution 2. Division by 2 is equivalent to right shift by 1 bit. Check the modulo by 2 is equivalent to check the least significant bit of the integer.
No comments:
Post a Comment