[LeetCode] 231. Power of Two
Given an integer, write a function to determine if it is a power of two.
Thought process:
If the number is not positive, return false directly. Divide the number by 2 until it becomes an odd number. If it's not 1, return false. Otherwise, return true.
Solution:
Time complexity: O(logn).
Thought process:
If the number is not positive, return false directly. Divide the number by 2 until it becomes an odd number. If it's not 1, return false. Otherwise, return true.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution { public: bool isPowerOfTwo(int n) { if (n <= 0) { return false; } while (!(n & 1)) { n /= 2; } return n == 1; } }; |
Time complexity: O(logn).
Comments
Post a Comment