-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisPowerOfTwo.py
More file actions
48 lines (41 loc) · 852 Bytes
/
isPowerOfTwo.py
File metadata and controls
48 lines (41 loc) · 852 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
39
40
41
42
43
44
45
46
47
48
'''
Source : https://leetcode.com/problems/power-of-two/description/
Author : Yuan Wang
Date : 2018-07-14
/***************************************************************************************
*Given an integer, write a function to determine if it is a power of two.
*
*Example 1:
*
*Input: 1
*Output: true
*Explanation: 20 = 1
*Example 2:
*
*Input: 16
*Output: true
*Explanation: 24 = 16
*Example 3:
*
*Input: 218
*Output: false
****************************************************************************************/
'''
#Time complexity:O(logn)
def isPowerOfTwo(n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
while(n>1):
if n % 2 != 0:
return False
n=n//2
return True
#Bitwise operation
def isPowerOfTwo(self, n: int) -> bool:
return (n != 0) and ((n & (n-1)) == 0)
n=218
print(isPowerOfTwo(n))