LeetCode No.231 Power of Two

Given an integer, write a function to determine if it is a power of two.

===================================================================

題目鏈接:https://leetcode.com/problems/power-of-two/

題目大意:判斷一個數是否爲2的冪。

思路:位操作。

參考代碼:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章