描述 Given an integer, write a function to determine if it is a power of two.
分析 如果是power of two, 則2進(jìn)制表達(dá)中,有且僅有一個(gè)1. 可以通過(guò)移位來(lái)數(shù)1的個(gè)數(shù), 這里用了一個(gè)巧妙的辦法, 即判斷 N & (N-1) 是否為0.
代碼
class Solution {public: bool isPowerOfTwo(int n) { return n > 0 && ((n & (n -1)) == 0); }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注