星期三, 二月 24, 2016

231. Power of Two

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

 

解题思路:

题目要求给定一个数,判断是否为2的幂次方。

首先,若该数为2的幂次方,则该数一定为正,故第一条件为n>0

方法一:若该数位2的幂次方,则使用二进制表示时,只有在最高位为1,其余都为0,而n&(n-1)得到的值为n去掉最低位的1后得到的数,若为2的幂次方,则进行该操作后应等于0.

//costs 8ms

class Solution {

public:

    bool isPowerOfTwo(int n) {

        return (n>0)&&((n&(n-1))==0);

    }

};

方法二:根据方法一,可知只要判断二进制表示时,1的数目为1即可。c++中的STL bitset可将n表示为二进制,其count方法可以用来计算1的数目。

// costs 4ms

class Solution {

public:

    bool isPowerOfTwo(int n) {

        return (n>0)&&(bitset<sizeof(n)*8>(n).count()==1);

    }

};

 

没有评论:

发表评论