leetcode之Power of Two

来源:互联网 发布:西门子plc编程入门教程 编辑:程序博客网 时间:2024/05/23 15:47

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的幂,这里利用的是二进制的方法,如果一个数为2的幂,则只有首位为1,所以与其减一的结果相与的结果为0。

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


1 0
原创粉丝点击