diff --git a/solutions/0200-0299/0231-power-of-two-easy.md b/solutions/0200-0299/0231-power-of-two-easy.md index 3d28f0fc235..a16cadd8af4 100644 --- a/solutions/0200-0299/0231-power-of-two-easy.md +++ b/solutions/0200-0299/0231-power-of-two-easy.md @@ -1,5 +1,6 @@ --- description: 'Author: @wingkwong, @vigneshshiv, @radojicic23 | https://leetcode.com/problems/power-of-two/' +tags: [Math, Bit Manipulation, Recursion] --- # 0231 - Power of Two (Easy) @@ -125,3 +126,36 @@ var isPowerOfTwo = function(n) { + +## Approach 2: Binary Search + +Almost same as the solution in 326. Power of Three and 342. Power of Four. + + + + + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + // the idea is to use binary search to find x to see if 2 ^ x = n is true or false + int l = 0, r = (int) log(pow(2, 31)) / log(2); + while (l < r) { + // get the middle one + // for even number of elements, take the lower one + int m = l + (r - l) / 2; + // exclude m + if (pow(2, m) < n) l = m + 1; + // include m + else r = m; + } + // check if 2 ^ l is n + // if so, then n is a power of two, otherwise it is not + return pow(2, l) == n; + } +}; +``` + + + \ No newline at end of file