Swift算法3-power of 2

Given an integer, write a function to determine if it is a power of two.
四種方法:(可以看一下迭代和遞歸的區(qū)別)

  1. 迭代 O(log n):
class Solution {
    func isPowerOfTwo(var n: Int) -> Bool {
    if (n == 0) {
        return false
    } else {
        while (n % 2 == 0) {
            n /= 2
        }
    }
    return (n == 1)
    }
}
  1. 遞歸 O(log n):
class Solution2 {
    func isPowerOfTwo1(var n: Int) -> Bool {
        return n > 0 && (n == 1 || (n % 2 == 0 && isPowerOfTwo1(n / 2)))
    }
}

3.bit O(1):
因為2的n次方的二進(jìn)制表示法 & 2的n次方-1的二進(jìn)制表示法 的值為0

class Solution {
    func isPowerOfTwo(n: Int) -> Bool {
    return n > 0 && (n & (n - 1) == 0)
    }
}
  1. Math O(1):
    Because the range of an integer = -2147483648 (-2^31) ~ 2147483647 (2^31-1), the max possible power of two = 2^30 = 1073741824.

(1) If n is the power of two, let n = 2^k, where k is an integer.

We have 2^30 = (2^k) * 2^(30-k), which means (2^30 % 2^k) == 0.

(2) If n is not the power of two, let n = j*(2^k), where k is an integer and j is an odd number.

We have (2^30 % j*(2^k)) == (2^(30-k) % j) != 0.

class Solution {
    func isPowerOfTwo(n: Int) -> Bool {
    return n > 0 && (1073741824 % n == 0)
    }
}

But is the last solution do-able?
I don't like the last solution!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 選取天天果園 PC Banner分析: 目的:以獼猴桃為主要對象,吸引用戶點擊,瀏覽,直至商品交易環(huán)節(jié); 對象:對...
    張文武貝閱讀 359評論 0 0
  • 學(xué)習(xí)來源:CNTV?網(wǎng)資 學(xué)習(xí)時段:大三上學(xué)年 今天我們將一起走進(jìn)數(shù)落在民間的,卻經(jīng)歷了千百年歷史文化變遷的古老城...
    信香閱讀 256評論 0 1
  • 昨天一天在兩處看到了有關(guān)麥當(dāng)勞的記憶。 先是豆瓣上看到作家米周寫了麥當(dāng)勞在小時候的記憶里簡直是一種高貴的食物,幾乎...
    小山羊的二三言閱讀 618評論 0 0

友情鏈接更多精彩內(nèi)容