2020年6月8日 星期一

Leetcode題解 Python & C#:六月挑戰DAY8 Power of Two

給一個整數,回傳該數是否為 2 的次方。

除了要注意整數 0 與負整數,其他整數都比較沒有問題。

2 的零次方是 1 ,而負次方都位於[0, 1]之間,也不是整數。所以只需要考量零以上次方要怎麼找。

如果是二的次方,除以二的餘數皆為 0,用此條件,只要餘數為 1 就不是 2 的次方。一直除到變成 1 (2**0)時,確定輸入是 2 的次方。

換一種進位,以「二進位」來看,二的次方,只會有一個bit為 1,最高位的bit為1,其餘為 0 ,所以只要判斷是否bit只存在一個1。

Python(除二餘數)
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n <= 1: return n == 1
        return self.isPowerOfTwo(n//2) if n % 2 == 0 else False
Python(bit存在只有1個1)
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n < 1: return False
        while n & 1 == 0:
            n >>= 1
        return n >> 1 == 0 
Python(最高位為1)
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and n == (1 << (n.bit_length()-1)) 
C#
public class Solution {
    public bool IsPowerOfTwo(int n) {
        if(n <= 1){return n == 1;}
        return n % 2 == 0 ? IsPowerOfTwo(n/2): false;
    }
}