LeetCode 231 Power of Two(三解)

231. Power of Two

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

我的方法是暴力求解,循环让1一直乘以2,如果结果等于n,且n大于0则输出true。这是最容易想到的方法

class Solution {
public:
    bool isPowerOfTwo(int n) {
         int result=1;
       for(int i=0;i!=1000;i++)
        {
            if(result==n &&n>0)
            {
            return true;
            }
            result*=2;
        }
        return false;
    }
};
搜索网上的资料发现更巧妙的方法,利用到了十六进制的特点(2的 N次幂的特点:仅有首位为1,其余各位都为0.

class Solution {
public:
    bool isPowerOfTwo(int n) {
        int cnt = 0;
        while (n > 0) {
            cnt += (n & 1);
            n >>= 1;
        }
        return cnt == 1;
    } 
};

或者

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n > 0) && (!(n & (n - 1)));
    } 
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值