- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathPowerOfTwo231.java
More file actions
Latest commit
38 lines (34 loc) · 724 Bytes
/
Copy pathPowerOfTwo231.java
File metadata and controls
38 lines (34 loc) · 724 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Given an integer, write a function to determine if it is a power of two.
*
* Example 1:
* Input: 1
* Output: true
* Explanation: 2^0 = 1
*
* Example 2:
* Input: 16
* Output: true
* Explanation: 2^4 = 16
*
* Example 3:
* Input: 218
* Output: false
*/
publicclassPowerOfTwo231 {
publicbooleanisPowerOfTwo(intn) {
if (n <= 0) returnfalse;
while (n > 1) {
if (n % 2 != 0) returnfalse;
n /= 2;
}
returntrue;
}
/**
* https://leetcode.com/problems/power-of-two/discuss/63974/Using-nand(n-1)-trick
*/
publicbooleanisPowerOfTwo2(intn) {
if (n<=0) returnfalse;
return (n & (n-1)) == 0;
}
}