1. 程式人生 > >LeetCode 231. Power of Two (演算法,計算二進位制數中1的位數)

LeetCode 231. Power of Two (演算法,計算二進位制數中1的位數)

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

輸入一個數,判斷其是否為2的冪。

思路:可以按照326題的思路,用換底公式計算。也可以根據2進位制的特點,2的冪一定是最高位是1,其他位是0。因此可以使用461題的技巧:n&(n-1)來計算1的個數。
這裡使用另一個方法:利用STL的bitset模板直接求解。

關於bitset的參考:http://www.cppblog.com/ylfeng/archive/2010/03/26/110592.html

    bool isPowerOfTwo(int n) {
        bitset<100> a(n);
        return a.count()==1;
    }