Skip to content

Commit 9852af2

Browse files
committed
231 Power of Two
1 parent c8fdb07 commit 9852af2

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@
125125
+ [217 Contains Duplicate(hashset)](algorithms/ContainsDuplicate)
126126
+ [219 Contains Duplicate II(hashmap)](algorithms/ContainsDuplicateII)
127127
+ [226 Invert Binary Tree(递归,树)](algorithms/InvertBinaryTree)
128+
+ [231 Power of Two(位运算,二进制1的个数)](algorithms/PowerofTwo)
128129

129130
## Database
130131

algorithms/PowerofTwo/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
## Power of Two
2+
3+
Given an integer, write a function to determine if it is a power of two.
4+
5+
Credits:
6+
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
7+
8+
## Solution
9+
10+
位运算,一个数是2的幂,则它的二进制1的个数等于1
11+
12+
求一个数二进制的1的个数的方法是不断地`n &= (n - 1)`,直到n为0
13+
14+
考虑以下两种情况:
15+
16+
* `n == 0`, 此时`n & (n - 1) == 0`, 但不是2的幂
17+
* `n=-2147483648`,此时二进制1的个数也等于1,但它不是2的幂
18+
19+
综合可以得出:只要`n <= 0`, 就一定不是2的幂。
20+
21+
因此最后解决方案为:
22+
23+
```c
24+
bool isPowerOfTwo(int n)
25+
{
26+
if (n <= 0)
27+
return false;
28+
return !(n & (n - 1));
29+
}
30+
```

algorithms/PowerofTwo/solve.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#include <stdio.h>
2+
#include <stdbool.h>
3+
#include <stdlib.h>
4+
bool isPowerOfTwo(int n)
5+
{
6+
if (n <= 0)
7+
return false;
8+
return !(n & (n - 1));
9+
}
10+
int main(int argc, char **argv)
11+
{
12+
int n;
13+
while (scanf("%d", &n) != EOF) {
14+
printf("%d\n", isPowerOfTwo(n));
15+
}
16+
return 0;
17+
}

0 commit comments

Comments
 (0)