您的位置:首页 > 其它

LeetCode题解:Power of Two

2015-08-12 10:47 113 查看
Given an integer, write a function to determine if it is a power of two.

题意:给定一个整数,判断是否为2的幂

解决思路:如果一个整数n是2的幂,那么让n和n-1进行与运算必然为0(位运算)

代码:

public boolean isPowerOfTwo(int n) {
        return ((n & (n-1))==0 && n>0);
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: