這題也是#Easy,也有先稍微喵過題目挑覺得有把握寫來解,想說先把會的題目先解完,再解其他的
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
這題我最一開始想到的作法是:不停除2,直到除二後的餘數是0的話就是true,如果除二的餘數是奇數的話要回false
程式碼應該會像這樣:
def isPowerOfTwo(self, n: int) -> bool:
while n > 0:
if n % 2 == 0:
n = n // 2
elif n == 1:
return True
else:
return False
果然run和submit都正常~附上submit結果: