-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProblem1_Power of Two_231.py
More file actions
30 lines (23 loc) · 1016 Bytes
/
Problem1_Power of Two_231.py
File metadata and controls
30 lines (23 loc) · 1016 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
# UCLA ACM ICPC: Interview Track Leetcode Problem Solutions
# Disclaimer: This is not the only valid solution and we do not claim our solutions
# to be optimal in terms of runtime or memory usage, we are merely giving example
# solutions to questions for learning purposes only
# Power of Two
# Leetcode Problem 231
# https://leetcode.com/problems/power-of-two/
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
# 0 is not a power of two and is an edge case that would cause an
# infinite loop in our while loop below, so we handle it here
if n == 0: return False
# while n is divisible by 2, divide n by 2
while n % 2 == 0:
n /= 2
# if n is a power of 2, at one point the loop above will have gotten
# to a point where n is 2, and 2 / 2 = 1 and 1 % 2 != 0, so
# return true if n == 1 and false if n != 1
return n == 1