231. Power of Two

来源:互联网 发布:网络组件设备方案 编辑:程序博客网 时间:2024/05/17 02:09

题目

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.


思路

判断一个数是否是2的指数,本质上就是判断此数是否是正数,且bit只有一个为1


代码

class Solution {public:    bool isPowerOfTwo(int n) {        //判断入参是不是2的指数,就是二进制bit只有一个1        //题目转化为判断入参的bit是否是正数且只有一个1,        if(n <= 0)        {            return false;        }        return !(n&(n-1));    }};
0 0
原创粉丝点击