File tree Expand file tree Collapse file tree 3 files changed +48
-0
lines changed Expand file tree Collapse file tree 3 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 125
125
+ [ 217 Contains Duplicate(hashset)] ( algorithms/ContainsDuplicate )
126
126
+ [ 219 Contains Duplicate II(hashmap)] ( algorithms/ContainsDuplicateII )
127
127
+ [ 226 Invert Binary Tree(递归,树)] ( algorithms/InvertBinaryTree )
128
+ + [ 231 Power of Two(位运算,二进制1的个数)] ( algorithms/PowerofTwo )
128
129
129
130
## Database
130
131
Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments