Skip to content

Commit

Permalink
solutions: 0231 - Power of Two (Easy)
Browse files Browse the repository at this point in the history
  • Loading branch information
wingkwong committed Feb 19, 2024
1 parent 93d4157 commit 4fd0acd
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions solutions/0200-0299/0231-power-of-two-easy.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down Expand Up @@ -125,3 +126,36 @@ var isPowerOfTwo = function(n) {

</TabItem>
</Tabs>

## Approach 2: Binary Search

Almost same as the solution in 326. Power of Three and 342. Power of Four.

<Tabs>
<TabItem value="cpp" label="C++">
<SolutionAuthor name="@wingkwong"/>

```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;
}
};
```
</TabItem>
</Tabs>

0 comments on commit 4fd0acd

Please sign in to comment.