leetcode 231: Power of Two

Use shift to determine. Be careful when n is 1 or a negative number.

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<=0)
            return false;
        while(n)
        {
            if(n>1&&n&1)
                return false;
            n>>=1;
        }
        return true;
    }
};


發佈了186 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章